[英]regex pattern match
I am using java regex library to find a pattern "String_OneOrMoreDigits". 我正在使用java正则表达式库来查找模式“String_OneOrMoreDigits”。 For example, "linenumber_1" or "linenumber_31" or "linenumber_456".
例如,“linenumber_1”或“linenumber_31”或“linenumber_456”。 I am trying the following pattern assuming I will get string of type "linenumber_2" or "linenumber_44".
我正在尝试以下模式,假设我将获得“linenumber_2”或“linenumber_44”类型的字符串。 However, I just get the strings of type "linenumber_2", it does not match more than one number at the end.
但是,我只是得到“linenumber_2”类型的字符串,它最后不匹配多个数字。 How to go about matching such strings?
如何匹配这些字符串?
Pattern pattern = Pattern.compile("(linenumber_[0-9])|(linenumber_[0-9][0-9])");
No need for an alternation, just use a "one or more" qualifier on the [0-9]
: 无需替换,只需在
[0-9]
上使用“一个或多个”限定符:
Pattern pattern = Pattern.compile("linenumber_[0-9]+");
That will match "linenumber_1" and "linenumber_44" and "linenumber_12345984". 这将匹配“linenumber_1”和“linenumber_44”和“linenumber_12345984”。 If you only want to match one or two digits, you can do that by being more explicit about the number of digits allowed:
如果你只想匹配一个或两个数字,你可以做到这一点的是更加明确的允许的位数:
Pattern pattern = Pattern.compile("linenumber_[0-9]{1,2}");
to add on if you want specific amount of digits, instead of 要添加,如果你想要特定的数字,而不是
Pattern pattern = Pattern.compile("linenumber_[0-9]{1,2}");
you could also use 你也可以用
Pattern pattern = Pattern.compile("linenumber_[0-9]{1|4|8}");
which would specify that you want either 1 digit, 4 digits or 8 digits. 这将指定您想要1位,4位或8位数。 and like Crowder said,
和克劳德说的那样,
Pattern pattern = Pattern.compile("linenumber_[0-9]+");
would match with any number of digits. 将匹配任意数量的数字。
you can also use: 你也可以用:
Pattern pattern = Pattern.compile("linenumber_\d+");
and if you need a case insensitive match, append (?i)
at the start like this: 如果你需要不区分大小写的匹配,请在开头追加
(?i)
,如下所示:
Pattern pattern = Pattern.compile("(?i)linenumber_\d+");
(?i)
allows regex engine to perform case insensitive match. (?i)
允许正则表达式引擎执行不区分大小写的匹配。 \\d
would match any digit from 0 to 9
\\d
将匹配0 to 9
任何数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.