barryedmund
barryedmund

Reputation: 612

JavaScript regex whitespace

Running the following JavaScript code finds, for example, "12 December" successfully.

return messageHtmlBody.match(/[1-31]{1,2}(\s)[a-zA-Z]{3,9}/i)[0];

I would like to return "12 December 2012" so tried this code:

return messageHtmlBody.match(/[1-31]{1,2}(\s)[a-zA-Z]{3,9}(\s)\d{4}/i)[0];

Not only did this not return the match, but the code didn't even run successfully. I tried the following too (just the second (\s) character) and that didn't run either:

return messageHtmlBody.match(/[1-31]{1,2}(\s)[a-zA-Z]{3,9}(\s)/i)[0];

Is there a reason why the second (\s) wouldn't work? The first (\s) matches the first white space successfully. The search string 100% contains the string "12 December 2012" so finding it should not be the issue.

Any ideas?

Upvotes: 0

Views: 457

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

[1-31] is not the valid regex for "a number between 1 and 31". All it does is accept any of 1, 2, 3 and (with the quantifier) any of 11, 12, 13, 21, 22, 23, 31, 32, 33.

Instead, it should be (?:3[01]|[1-2][0-9]|[0-9])

Also, it is unnessecary to put parentheses around the \s.

To be more specific, you could also explicity state what months are with:

(?:(?:jan|febr)uary|march|april|may|june|july|august|(?:(?:sept|nov|dec)em|octo)ber)

Upvotes: 1

utapyngo
utapyngo

Reputation: 7146

[1-31]{1,2} won't match what you want. It is equivalent to [1-3]{1,2}.

Thy to test your expressions using a regex tool like regexpal.

Upvotes: 0

Related Questions