4

I return the following string from a webpage

Order Number: 1509596 Customer Number: 8

but it could also be

Order ID 1509596 Customer 8

I want to use regex so in my method I just return the order number, I was doing

orderNumber.replaceAll("[^0-9]", "")

but that obviously doesn't work because I then have an 8 on the end of my order number. Can somebody help me how I would just the order number as I'm rubbish at reg ex!

The string will always be 50 characters long but the order number is dynamic so I don't know how long it will be, is it possible to just return the first number in the string?

2
  • You should be able to use the "[0-9]+" regex to match the first number in your string. Commented Jan 29, 2014 at 10:04
  • Would be better to do a regex match on sequences of numbers, and select the index of the one you want. If you continue the way you are doing it, this regex could work... Customer.+|[^0-9] Commented Jan 29, 2014 at 10:05

3 Answers 3

8

Use a regex that matches the whole input, capturing the part you want, then replace everything captured to "extract" what you want.

String firstNumber = str.replaceAll("^\\D*(\\d+).*", "$1");

See live demo.

The regex matches all leading non-digits (if any), then as many digits as are found next as capture group 1, then matches to the end. $1 is a back reference to capture group 1.


If newlines (which dot does not match by default) are in the input, enable DOTALL flag by adding (?s) to the regex:

String firstNumber = str.replaceAll("(?s)^\\D*(\\d+).*", "$1");
Sign up to request clarification or add additional context in comments.

2 Comments

When new line exist on string, this method not work correctly.
@SaeidZ See edited answer for how to cater for newline characters.
1

I can't think of a single line that would accomplish this, but the following should work:

String orderString = "Order Number: 1509596 Customer Number: 8";
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(orderString);
if (m.find())
{
  String orderNr = m.group();
  System.out.println(orderNr);
}

3 Comments

Can't think of how to do it in one line? See this... muhahahaha
You can simply use String orderNr = m.group()
@BackSlash: thank, I thought group() could only be used when there were explicit groups (using (..)) in the regex.
0

if you change orderNumber.replaceAll("[^0-9]", "")

to

orderNumber.replaceAll("[^0-9]", ",") hence

you will get ,1509596,8 as an answer,

I think this is probably help you to solve ans.

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.