Search code examples
javascriptregexstringend-of-line

Regex not validating end of string


Consider the following scenario (Javascript code):

regex = new RegExp((/([\d,.]+)[ $]/));
value = "2.879"  

The regexp doesn't match value, but it matches (value+" ") therefore i think that the $ is not matched? Why is that?

Shouldn't the $ validate the end of string?


Solution

  • Special characters like $ don't have the same meaning inside a character class. In a character class they're just characters, so [ $] will match either the space character or the $ character. It won't match the end of a string.

    If you want to match either a space character or the end of the string, you should use alternation, i.e. ( |$).