简体   繁体   中英

java regular expression optional characters

I'm having problems getting my regular expression working.

The regular expression is:

([0-9]m)* ([0-9]f)*

A digit must come before "m" or "f" but "m" or "f" are optional. Example are:

1m 2f
1m
6f

What have I done wrong?

The * means match the previous token 0 or more times, which doesn't look like what you want.

These should help you to build the regular expression you need:

  • ? to mean 0 or 1 matches.
  • | for alternation.
  • (?:...) for a non-capturing group.
  • ^ and $ to anchor at the start and end of the string.

Knowing that, I imagine that you can probably find a solution by yourself, but for the sake of completion, I'll show one possible solution.


Your question isn't very clear so I'm just going to assume that you want the following to match:

1m 2f
1m
6f 
0m

and that you want the following to fail to match:

1
m    
11m
1m 1m
2f 3m
1m  2f
"1m 2f"

If those assumptions are incorrect, then please make your question more clear.

With those assumptions, try this:

^[0-9]m(?: [0-9]f)?$|^[0-9]f$

If you also want 2f 3m to match then use this:

^[0-9]m(?: [0-9]f)?$|^[0-9]f(?: [0-9]m)?$

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