简体   繁体   中英

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?

[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)

[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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM