Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex getting the first instance of a number from a string

Tags:

java

regex

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?

like image 965
Doctor Who Avatar asked Nov 16 '25 18:11

Doctor Who


1 Answers

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");
like image 120
Bohemian Avatar answered Nov 18 '25 08:11

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!