I am trying (\d+|\d+\.\d+)
on this sample string:
Oats 124 0.99 V 1.65
but it is giving me decimal number in different groups when I am using pattern matcher classes in Java.
I want my answers in a single group.
How to extract numbers from a string using regex in Java? Extracting all numeric data from the string content is a very common and useful scenerio and can be achieved using a regex pattern. The basic pattern we need to use is a “ [0-9]”, i.e. character class of digits from 0 to 9.
Java Regex. The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.
Regex for Decimal Numbers 1 General Format of a Decimal Number. To accurately describe what a decimal number should look like, we need to use a split definition. ... 2 Regular Expressions for Decimal Numbers. Let’s work on the first part of the definition. ... 3 Other Considerations. ... 4 Which Flags to Use. ... 5 Sources. ...
For integer number : Below is the regular definition for an integer number. sign -> + | - | epsilon digit -> 0 | 1 | .... | 9 num -> sign digit digit* Hence one of the regular expression for an integer number is
You don't need to have a separate patterns for integer and floating point numbers. Just make the decimal part as optional and you could get both type of numbers from a single group.
(\d+(?:\.\d+)?)
Use the above pattern and get the numbers from group index 1.
DEMO
Code:
String s = "Oats 124 0.99 V 1.65";
Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(1));
}
Output:
124
0.99
1.65
Pattern explanation:
()
capturing group . \d+
matches one or more digits.(?:)
Non-capturing group.
(?:\.\d+)?
Matches a dot and the following one or more digits. ?
after the non-capturing group makes the whole non-capturing group as optional.OR
Your regex will also work only if you change the order of the patterns.
(\d+\.\d+|\d+)
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With