0

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?

2
  • Should 2f 1m be allowed? What about 2m 1m? What about 11m? Commented Apr 29, 2012 at 20:16
  • 1
    When you say "m" or "f" are optional, is 1 ok by itself? Commented Apr 29, 2012 at 20:17

1 Answer 1

9

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)?$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.