Hot answers tagged

45

Firstly, Python has a style guide and (unless you're given a different guide, in which case please provide a link to it) you should follow it. Your code generally follows it, but note that the imports are in the wrong order, it should be: from collections import Counter import re import sys import numpy as np Note alphabetical order, and a split between ...


38

function fuzzy_match(str,pattern){ pattern = pattern.split("").reduce(function(a,b){ return a+".*"+b; }); return (new RegExp(pattern)).test(str); }; String concatenation is slow. The reason is that you need to allocate new memory anytime you concatenate two strings. A smart compiler may optimise that, but not too much. However, what you are trying ...


34

I remember having read somewhere (possibly in another Code Review answer) that for an e-mail address, the simplest and most effective validation you can do is to make sure it contains an @. Making it more restrictive than that can often be a risk of invalidating some valid e-mails. You'd be surprised at some examples of valid e-mail addresses. As an ...


33

.*?;.*? will cause catastrophic backtracking. See this post on more details on the problem: http://www.regular-expressions.info/catastrophic.html To resolve the performance issues, remove .*?; and replace it with [^;]*;, that should be much faster.


33

In general, it is bad practice to perform string substitutions in multiple passes, feeding the output back of one substitution into another round of substitutions. (Here is an example of how multiple-pass substitutions can lead to incorrect results.) In this case, it happens to be safe, since none of the outputs overlap with any of the patterns, but I ...


32

Congratulations, what you have here is a case of really really bad backtracking. Remember the StackOverflow outage in July 2016? Because it's explained quite nicely there. regex101 is so kind as to tell us in the debugger view how many steps the regex takes until it matches. In case you were wondering, it's 111,803 We can drastically reduce the number of ...


25

Your problem is an interesting one,but your solution is not a great use of regular expressions, since there's the better option of using the 'word boundary' anchor \b. The boundary anchor matches a transition from a word, to a non-word, or vice versa. For this purpose, using the \w match to target word-characters after the \b is the right solution. Note ...


22

Regex.Matches returns a MatchCollection which contains Matches which captures the index and length of each match. So as such you won't have to fire up the regex engine again because you can do something like this: string toSearchInside; // The actual string I'm going to be replacing within List<string> searchStrings; // The list of words to look for ...


21

The Regex expression [^0-9.] matches anything other than 0 to 9 and .. If you remvoe the . from the expression, It should only match everything you want. But, this can be furthermore simplify to \D which matches anything but numbers. So the whole thing could be written in one line Regex.Replace(value, @"\D", "") I don't think it is worth to create a ...


20

As @Simon pointed out, your regular expression might consider some valid addresses as invalid. Per this source which I've found somewhere on this Stack Overflow page, this would be RFC5322-compliant: (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)* | "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f] | \\[\x01-\x09\...


20

Split the regex into smaller parts to check each rule individually. Here's the code for JavaScript. The same simple logic can be used for Ruby or any other language. // Check the length if (str.length >= 8 && validate()) { } // Check if all the characters are present in string function validate(string) { // Initialize counter to zero ...


19

My solution for this is not unique to Ruby - if you have a list of substitutions you want to make, model them as a list (or array), and then loop over the list in your preferred fashion: def lisp(input) substitutions = [ [/s/, "th"], [/er/, "uh"], [/r|l/, "w"] ] substitution_helper(input.downcase, substitutions).capitalize end def ...


19

I'm not a fan of "sanitizing" data. There isn't a clear definition of what "sanitizing" means, other than that it takes untrustworthy input and somehow makes it valid. It might entail discarding the invalid parts of the input — which is not what you are doing here. Escaping is a clearer term to describe what you are doing. Repeated string concatenation ...


19

Be nice to the maintenance programmer, even (especially?) if you expect it to be you. If you're mixing characters which are visually indistinguishable but don't need to be literal self-representations, you can use Unicode escapes and hexadecimal offsets as so: convertNumbers2English: function (string) { return string.replace(/[\u0660-\u0669]/g, function ...


18

You should take a look at the possibility to name groups in regex patterns; your match pattern can then be a oneliner: const string pattern = @"^(?<name>\w+)\[(?<index>\d+)\]$"; Match match = Regex.Match(command[2], pattern); if (match.Success) { string featureName = match.Groups["name"].Value; int index = int.Parse(match....


17

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski A few things to be commented : Regular expressions might not be the right tool for this. .*?;.*?;.*?;.*?;.*?;.*?;.*?" is potentially very slow and might not do what you want it to do (it could match many more ; than what ...


17

I would very strongly recommend against using a regular expression for this. There is no clear mapping between the list of requirements you posted and the code. Imagine another developer looking at this. Are they able to deduce the list of requirements? Given the list of requirements, are they able to verify that the regular expression is correct? How long ...


17

I disagree with rolfl's assertion that, "There is no practical way to validate an e-mail address by regex alone." He is correct—as illustrated by the somewhat infamous SO answer he linked to—that it's impractical to validate any RFC-5322-compliant email addresses because, to quote the HTML5 spec: RFC-5322 … defines a syntax for e-mail addresses that is ...


16

Use split, like so: >>> filecontent = "13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234"; >>> items = filecontent.split(";"); >>> items; ['13P397', 'Fotostuff', 't', 'IBM', 'IBM lalala 123|IBM lalala 1234', '28.000 things', '', 'IBMlalala123|IBMlalala1234'] >>> I'm a bit ...


15

Your regex has many false positives (matches without a valid URL being there), and many false negativs (URLs you don't recognize). You should read the appropriate RFCs which contain relevant parts of the grammar. Here are some failure scenarios: ⊖ You don't match schemes other than HTTP or HTTPS. Consider FTP, SFTP, data URLs, and other widespread schemes ...


15

I agree mostly with @Vogel612's answer, the second version is more concise and there is no need to litter variables all over the place as is done in the first version. Another point is that code should be self-documenting, which @Vogel612 also suggests, but else you can still add a comment behind the code lines. My review I wanted to talk about a more ...


15

There are a number of things that could be improved here. You're doing the right thing with the pre-compiled regular expression/pattern, but, you have fallen victim to the little-known auto-format-muck-up-monster, and what I consider the magic-value-overcompensation issue: private static final String SIMPLE_SENTENCE = "([a-zA-Z]+(\\.|\\. |'(s |re |...


15

Overall, this looks like pretty good JavaScript code. I would have two comments though, to avoid errors, long term (i.e. maintainability): Direct Statement if(expr) statement; This is correct in all C-like languages, unfortunately. Only, if you write two statements after the if() and forget to add the curly brackets, you end up with a bug. I always write ...


15

Problems I'm not sure that TextFileWordSplitter is a good name for the class, especially since the source of the text is, in general, a network resource rather than a java.io.File. List<String> wordList = new ArrayList(); should be List<String> wordList = new ArrayList<>(); to suppress a compiler warning. The readUrlTextContent() ...


15

Stop. Close Excel. Take a deep breath. Now go and get an actual Database. MS Access. MySQL is free and Open-Source. It doesn't really matter. What matters is that Excel is not the program to be doing this in. At all. 10-Dimensions was already excessive. 31 is a severe case of Over-Engineering. Unless you've been specifically required to include support ...


15

Not duplicating any of @Peilonrayz's code review points ... Stop reading entire files into memory when you can process the file line by line in one pass, and stop creating huge lists in memory which are then iterated over exactly once. Both of these things creates a huge unnecessary memory pressure which can be avoided by looping and/or using generator ...


14

When you're in an interview, few interviewers expect you to come up with the perfect solution. Mainly, they're looking for an idea of how you think and how you approach a problem. Especially as a junior programmer. Approaching the problem from a test driven perspective first might seem the logical way, but what about just writing the code to solve the ...


14

The single sign of over thinking was your use of a business primitive (PhoneNumberManager). The problem called for you to start with a string and end with a string so no need for an extra type in the middle. It looks like it also caused you to miss the obvious string extension approach. Getting the Regex wrong is normally ok in interviews since almost ...


14

You can combine px and em into a single group You can pull in the negation sign with a ? [0-9] is equivalent (usually) to \d ^ and $ can be pulled out to the end (or use the api than only matches the entire string. this results in: ^(-?\d+(px|em)|\d+%|auto|0)$ If you can have a negative % values then it's even simpler: ^(-?\d+(px|em|%)|auto|0)$


14

In splitTextStringIntoWordList I found myself having to split textString param into String[] array, and immediately afterwards adding the elements from the array one at a time, parsing with regex, into a List<String>. Is there a better way to do this that might not need as much manipulation? Wells, in Java 8... List<String> result = Pattern....


Only top voted, non community-wiki answers of a minimum length are eligible