How to use a predictive expression in a regular expression to match without a character?

I have a set of regular expressions inside a function that works pretty well for me, but I came across a new pattern where they fail. This function does not work when there are more characters in the string. For example, my function matches and replaces the text as follows: " 1 m is equivalent to... " becomes " 1 meter is equivalent to... " However, it does not work: " There are 100 cm in 1 m "

I am using AS3, which I assume has a regex mechanism, almost equivalent to JavaScript. Current template:

 [0-9]+ m(?= )|[0-9]+m(?= ) 

I am looking at a list of patterns and replacement strings, so it was easy to add another pattern to the list. I tried:

 [0-9]+ m(?=)|[0-9]+m(?=) 

and

 [0-9]+ m(?='')|[0-9]+m(?='') 

And both failed. I lack the fundamental brevity of knowledge. I believe that I need to know how to say: "look ahead and match when there are no other characters in the string"

+4
source share
3 answers

You can simplify your expression by looking for the word boundary ( \b ); something like that:

 var regex = /(\d+)\s*m\b/; regex.exec('1 m is equivalent to...'); // => ["1 m", "1"] regex.exec('There are 100 cm in 1 m'); // => ["1 m", "1"] 
+3
source

"No other characters in the string are equivalent to" end of line ", so use the $ metacharacter

+1
source

You are looking for a phrase that is represented by the sequence \b . You can use the expression /\d+\s*m\b/

 \d+ - one or more digits \s* - any number of spaces m - a literal 'm' \b - a word boundry 
0
source

All Articles