Psychosupreme Psychosupreme - 5 months ago 8
Java Question

Regex that removes everything but the number

I am trying to use java's

string.replaceAll()
or
replaceFirst()
methods in order to edit data from a pdf document. The line of data that is returned is:


21/1**E (6-11) 4479 77000327633 (U)


I wish to only store the
77000327633
into a variable and looking for the correct regex to replace everything else with
""
. I've tried searching around but nothing seems to give me my desired outcome.

Answer

It could be done like this:

String value = "21/1**E (6-11) 4479 77000327633 (U)";
Pattern pattern = Pattern.compile(".* (\\d{11}) .*");
System.out.println(pattern.matcher(value).replaceAll("$1"));

Output:

77000327633

NB: This assumes that your number has 11 digits and that there is a space before and after.

NB2: It is not meant to be perfect it is only to show the idea which is here to define a global pattern with a group and replace everything by the content of the group

Comments