Hi I am trying to build one regex to extract 4 digit number from given string using java. I tried it in following ways:
String mydata = \"get the 0025 data f
Pattern pattern = Pattern.compile("\\b[0-9]+\\b");
This should do it for you.^$
will compare with the whole string.It will match string with only numbers
.
You can go with \d{4}
or [0-9]{4}
but note that by specifying the ^
at the beginning of regex and $
at the end you're limiting yourself to strings that contain only 4 digits.
My recomendation: Learn some regex basics.
Change you pattern to:
Pattern pattern = Pattern.compile("(\\d{4})");
\d
is for a digit and the number in {}
is the number of digits you want to have.
If you want to match any number of digits then use pattern like the following:
^\D*(\d+)\D*$
And for exactly 4 digits go for
^\D*(\d{4})\D*$
If you want to end up with 0025,
String mydata = "get the 0025 data from string";
mydata = mydata.replaceAll("\\D", ""); // Replace all non-digits
Remove the anchors.. put paranthesis if you want them in group 1
:
Pattern pattern = Pattern.compile("([0-9]+)"); //"[0-9]{4}" for 4 digit number
And extract out matcher.group(1)