Grbe1l
Grbe1l

Reputation: 489

Regex to find instance of a number in a string

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 :)

Upvotes: 0

Views: 73

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

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());
}

DEMO

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

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));
}

Upvotes: 2

Related Questions