I have prepared this REGEX [_[/\\\d+]]
to get either of below
_
OR
/123
So when I try to match below are the results
_
(Matches -> OK)
/
(Matches -> OK)
/123
(Doesn't match -> Not OK)
What am I missing here?
You are using [
and ]
which denotes a character class which will match any of the listed a single time. Using \d+
will match either a digit or a +
char.
If you add a quantifier like +
to the character class itself you will repeat any of the listed but you will not have the OR logic.
You should use a pipe |
for the OR part which will match either an underscore OR a forward slash followed by 1+ digits.
To also match a single forward slash you could match 0+ digits using the *
instead of +
_|/\d+
Note to double escape the backslash in Java _|/\\d+
Use: _|\\d*
Explanation:
_ # an underscore
| # OR
/ # a slash
\\d* # 0 or more digits
You can simply use the pattern: _|/\\d*
The |
essentially combines two separate patterns into one, and will match if either side matches.
This will match:
_
/
/1
/12
/123
etc. If i understood right your question you want either:
Here my solution:
_|(/\\d+)
Meaning:
_
: underscore |
: or (
: beginning of capturing group \\d
: digit +
: one or more times )
: endof capturing group Hope this helps!
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.