0

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

2 Answers 2

2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.