简体   繁体   中英

Java regex how to match _, /, or /123?

I have prepared this REGEX [_[/\\\d+]] to get either of below

  • An underscore -> _

OR

  • A forward slash followed by some numbers /123

So when I try to match below are the results

  1. _ (Matches -> OK)

  2. / (Matches -> OK)

  3. /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+

regex demo

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:

  • one underscore
  • or a slash followed by one or more digits

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.

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