Reputation: 7653
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: it is also matching lines like WORD11a
, which I don't want.
Upvotes: 2
Views: 18320
Reputation: 7653
I forgot the $
end of line character, so it matched:
WORD1
WORD11
WORD11a
this works, just fine:
^WORD\\d*$
Upvotes: 3
Reputation: 1
"(\\AWORD[\\d]*$)" this should do the trick. beginning of input, your WORD, and a number
Upvotes: 0
Reputation: 420951
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"
Upvotes: 0