简体   繁体   English

Java正则表达式可选字符

[英]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. “ m”或“ f”之前必须有一个数字,但“ m”或“ f”是可选的。 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. *表示与上一个标记匹配0次或更多次,这看起来与您想要的不一样。

These should help you to build the regular expression you need: 这些应该可以帮助您构建所需的正则表达式:

  • ? to mean 0 or 1 matches. 表示0或1个匹配项。
  • | 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: 如果您还希望2f 3m匹配,请使用以下命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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