Regular expressions - Unable to match this string
I am writing a ruby script requiring pattern matching. I got most however I am unable to match a long string of 01122223_200000_1717181
so on using
/ (\d+\_+\d+)*/
.
It's matching with the following pattern though / \**|TYPE:|\=*/
. I can't figure out why. I have checked the ordering of the pattern matching too.
Does someone have any sug开发者_Python百科gestion?
You have more than one thing going on with your pattern, but I think only one is causing matching to fail:
- Your parentheses are slightly off.
- You have a
+
after the underscore, but I don't think you want/need one. - You have an extra whitespace at the beginning of the pattern.
Of these, probably the only issue preventing you from getting a match is the last one. The rest of the pattern should still match, though probably not quite the way you want it to (meaning it'll match some things you wouldn't want it to match). I'd go with this:
/\d+(_\d+)+/
If you want to accept a pattern with no underscores (e.g. 999999), use this:
/\d+(_\d+)*/
About your second question: The reason it's matching / \**|TYPE:|\=*/
is that \**
and \=*
use *
as a quantifier, rather than +
. That means they'll match even if the input contains no *
or =
characters at all. \=*
matches an empty string, so that expression will match any input. Change it to / \*+|TYPE:|\=+/
and it shouldn't match anymore.
For matching that first string (01122223_200000_1717181
) this might do the trick: /(\d+_)+\d+/
My more-or-less first idea was:
/\d+(_\d+)*/
It should be easy. Just use ranges.
/[\d_]*\d/
精彩评论