runtimeZero runtimeZero - 1 month ago 8
Javascript Question

Matching digits and text in a string using regular expression

Why does percent not get matched in the the following regular expression

/(^(?:[\d\.]+|first|second|goal))(?:\w+(interval|percent))?/i


Input string example:

10percentRule

Answer

/(^(?:[\d.]+|first|second|goal))(?:\w+(interval|percent))?/i

w+ is the problem here: you should use w*, w+ means 1 or more matches, while w* means 0 or more matches; in your example, 1st group captures the number digits, then searchs for at least 1 character (w+) brefore interval or percent,so, it doesn´t return any match.

Use w* instead, or even beter w*? (not-greedy), so it will stop searching characters when it find interval or percent

/(^(?:[\d.]+|first|second|goal))(?:\w*?(interval|percent))?/i