Hello I have a question about RegEx. I am currently trying to find a way to grab a substring of any letter followed by any two numbers such as: d09.
I came up with the RegEx ^[a-z]{1}[0-9]{2}$ and ran it on the string
sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0
However, it never finds r30, the code below shows my approach in Java.
Pattern pattern = Pattern.compile("^[a-z]{1}[0-9]{2}$");
Matcher matcher = pattern.matcher("sedfdhajkldsfakdsakvsdfasdfr30.reed.op.1xp0");
if(matcher.matches())
System.out.println(matcher.group(1));
it never prints out anything because matcher never finds the substring (when I run it through the debugger), what am I doing wrong?
There are three errors:
Your expression contains anchors.
^matches only at the start of the string, and$only matches at the end. So your regular expression will match"r30"but not"foo_r30_bar". You are searching for a substring so you should remove the anchors.The
matchesshould befind.You don’t have a group 1 because you have no parentheses in your regular expression. Use
group()instead ofgroup(1).Try this:
ideone
Matcher Documentation