Doctor Who
Doctor Who

Reputation: 1649

regex getting the first instance of a number from a string

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?

Upvotes: 4

Views: 5228

Answers (3)

Bohemian
Bohemian

Reputation: 424993

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

Upvotes: 8

user330315
user330315

Reputation:

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

Upvotes: 1

Pulah Nandha
Pulah Nandha

Reputation: 774

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.

Upvotes: 0

Related Questions