I am trying (\\d+|\\d+\\.\\d+)
on this sample string:
Oats 124 0.99 V 1.65
but it is giving me decimal number
Question not entirely clear, but the first problem I see is . is a magic character in regex meaning any character. You need to escape it with as . There are lots of regex cheat sheets out there, for example JavaScript Regex Cheatsheet
(\d+|\d+\.\d+)
Try this pattern:
\d+(?:\.\d+)?
Edit:
\d+ match 1 or more digit
(?: non capturing group (optional)
\. '.' character
\d+ 1 or more digit
)? Close non capturing group
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