java 正则表达式匹配单词,后跟零个或多个数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4353301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to match word, followed by zero or more digits?
提问by kofucii
I need a regular expression to match line beginning with a specific WORD
, followed by zero or more digits, then nothing more. So far I've tried this:
我需要一个正则表达式来匹配以特定 开头的行WORD
,后跟零个或多个数字,然后仅此而已。到目前为止,我已经尝试过这个:
^WORD\d{0,}
and this:
还有这个:
^WORD[0-9]*
But it doesn't work as expected: it is also matching lines like WORD11a
, which I don't want.
但它没有按预期工作:它也匹配像 那样的行WORD11a
,这是我不想要的。
回答by kofucii
I forgot the $
end of line character, so it matched:
我忘记了$
行尾字符,所以它匹配:
WORD1
WORD11
WORD11a
this works, just fine:
这有效,就好了:
^WORD\d*$
回答by aioobe
The problem is probably that ^
matches the beginning of the input (I suspect you only find a match if the first line matches), and not the beginning of a line.
问题可能是^
匹配输入的开头(我怀疑你只在第一行匹配时才找到匹配项),而不是一行的开头。
You could try using a positive lookbehind saying that the match should be preceded by either start of input (^
) or a new line (\n
):
您可以尝试使用积极的lookbehind 说匹配应该以输入开头 ( ^
) 或新行 ( \n
)开头:
String input = "hello156\n"+
"world\n" +
"hello\n" +
"hell55\n";
Pattern p = Pattern.compile("(?<=^|\n)hello\d*");
Matcher m = p.matcher(input);
while (m.find())
System.out.println("\"" + m.group() + "\"");
Prints:
印刷:
"hello156"
"hello"
回答by user3841723
"(\\AWORD[\\d]*$)" this should do the trick. beginning of input, your WORD, and a number
"(\\AWORD[\\d]*$)" 这应该可以解决问题。输入的开头、你的 WORD 和一个数字