Reputation: 895
I'm learning regex. When I match this:
\d[^\w]\d
on this
30-01-2003 15:20
I get 3 matches: 0-0, 1-2, 3 5, and 5:2.
When I try adding a question mark at the end of the regex (\d[^\w]\d?
), my matches don't change.
When I move the question mark to after the square bracket (\d[^\w]?\d
), the matches are now 30, 01, 20, 03, 15, and 20.
When I move the question mark to before the square bracket (\d?[^\w]\d
), my matches are the same as in the first case.
Why is this? I know the ?
operator marks the preceding character as optional, so I expected the behaviour in the second case, but not in the first or third.
Upvotes: 0
Views: 274
Reputation: 824
U just need it
-Two Solutions-
1. REGEXP:
\d+
1. Explanation:
\d =>numbers
+ => 1 or more
2. REGEXP
[0-9]+
2. Explanation
[0-9] <= Numbers
+ <= 1 or more
it will match all numbers (Solution 1 or 2)
Original Text:
30-01-2003 15:20
Result:
30
01
2003
15
20
Enjoy.
See: https://regex101.com/r/xXaLgN/6
Upvotes: 0
Reputation: 9597
Your first and third cases produce the same results as the original only because of the particular string you're searching - they are NOT equivalent searches in general. Specifically, every occurrence of \d[^\w]
in your string happens to be followed by a digit, so making the trailing digit optional does not change any of the matches. Likewise, every occurrence of [^\w]\d
happens to be preceded by a digit. If your string had two spaces together, or a doubled punctuation mark somewhere, the results would differ for each case.
Upvotes: 1
Reputation: 59699
Because ?
is a greedy match. It will attempt to consume as much as possible. So, if a \d
is present, it will always grab it.
Think of the ?
at the end as defining two regexes: \d[^\w]\d
and \d[^\w]
. In your test case, you never have a match where the first regex doesn't match and the second one does (without overlaps, again, it's greedy). That's why your matches never change. If, however, you changed your test case to this:
30-01-2003 15:20/
You'll get an extra match of 0/
depending on whether or not you include the question mark at the end of the regex.
Upvotes: 2