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\d{0,}
and this:
^WORD[0-9]*
But it doesn't work as expected开发者_JS百科: it is also matching lines like WORD11a
, which I don't want.
I forgot the $
end of line character, so it matched:
WORD1
WORD11
WORD11a
this works, just fine:
^WORD\\d*$
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
):
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"
"(\\AWORD[\\d]*$)" this should do the trick. beginning of input, your WORD, and a number
精彩评论