I have a string that is like the following
32686_8 is number 2
I am new to using regex and want some help. I want two different patterns, firstly to find
32686_8
and then another one to find
2
hope you can help :)
You can use the following to match:
([\\d_]+)\\D+(\\d+)
And extract out $1 and $2
See DEMO
Code:
Matcher m = Pattern.compile("^([\\d_]+)\\D+(\\d+)$").matcher(str);
while(m.find())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
}
Use capturing groups.
Matcher m = Pattern.compile("^(\\S+).*?(\\S+)$").matcher(str);
if(m.find())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
}
OR
Matcher m = Pattern.compile("^\\S+|\\S+$").matcher(str);
while(m.find())
{
System.out.println(m.group());
}
^\\S+ matches one or more non-space chars present at the start. Likewise, \\S+$ matches one or more non-space characters present at the end.
OR
Matcher m = Pattern.compile("\\b\\d+(?:_\\d+)*\\b").matcher(str);
while(m.find())
{
System.out.println(m.group());
}