match() returns array with two matches when I expect one match

From String.prototype.match [MDN]: If the regular expression does not include the g flag, returns the same result as regexp.exec(string). Where the RegExp.prototype.exec documentation [MDN] says: The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. So as you … Read more

Finding occurrences of a word in a string in python 3

If you’re going for efficiency: import re count = sum(1 for _ in re.finditer(r’\b%s\b’ % re.escape(word), input_string)) This doesn’t need to create any intermediate lists (unlike split()) and thus will work efficiently for large input_string values. It also has the benefit of working correctly with punctuation – it will properly return 1 as the count … Read more

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets. Try this… var str=”f 34 545 323 12345 54321 123456″, matches = str.match(/\b\d{5}\b/g); console.log(matches); // [“12345”, “54321”] jsFiddle. The word boundary \b is your friend here. Update My regex will get a number … Read more

Create new column in dataframe based on partial string matching other column

Since you have only two conditions, you can use a nested ifelse: #random data; it wasn’t easy to copy-paste yours DF <- data.frame(GL = sample(10), GLDESC = paste(sample(letters, 10), c(“gas”, “payroll12”, “GaSer”, “asdf”, “qweaa”, “PayROll-12”, “asdfg”, “GAS–2”, “fghfgh”, “qweee”), sample(letters, 10), sep = ” “)) DF$KIND <- ifelse(grepl(“gas”, DF$GLDESC, ignore.case = T), “Materials”, ifelse(grepl(“payroll”, DF$GLDESC, … Read more

Java: method to get position of a match in a String?

The family of methods that does this are: int indexOf(String str) indexOf(String str, int fromIndex) int lastIndexOf(String str) lastIndexOf(String str, int fromIndex) Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index]. String text = “0123hello9012hello8901hello7890”; String word = “hello”; … Read more

How to match a String against string literals?

UPDATE: Use .as_str() like this to convert the String to an &str: match stringthing.as_str() { “a” => println!(“0”), “b” => println!(“1”), “c” => println!(“2”), _ => println!(“something else!”), } Reason .as_str() is more concise and enforces stricter type checking. The trait as_ref is implemented for multiple types and its behaviour could be changed for type … Read more