vulpcod3z
vulpcod3z

Reputation: 194

Java: regex pattern that ignores any number that contains a decimal

I have a string match = "234 587.094";
What I need to find, using regex, is every integer in the string only.
When matched against a pattern, this should only return 234 because 587.094 is not an integer.

Here's the pattern I have so far:

Pattern int_p = "(\\d+[^(\\.?\\d+)])";

Upvotes: 2

Views: 937

Answers (3)

Shar1er80
Shar1er80

Reputation: 9041

You can try this pattern

"\\d+(\\.\\d+)?"

It matches both integers and decimals, but when you find a decimal you just ignore it.

public static void main(String[] args) throws Exception {
    String data = "234 587.094 123 3.4 6";
    Matcher matcher = Pattern.compile("\\d+(\\.\\d+)?").matcher(data);
    while (matcher.find()) {
        if (matcher.group(1) == null) {
            System.out.println(matcher.group());
        }
    }
}

Results:

234
123
6

UPDATE

Or you can strip out all of the decimal numbers with a replaceAll() with this pattern

"\\d+\\.\\d+"

Then you're left with just the integers for which you can use the pattern \\d+

public static void main(String[] args) throws Exception {
    String data = "234 587.094 123 3.4 6 99999.9999 876";

    // Remove decimal numbers
    data = data.replaceAll("\\d+\\.\\d+", "");

    Matcher matcher = Pattern.compile("\\d+").matcher(data);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

Results:

234
123
6
876

Upvotes: 5

Bohemian
Bohemian

Reputation: 424993

In one line, this code extracts the number if one is found, or blank if not:

String num = str.replaceAll(".*?(^|[^.\\d])(\\d+)?($|[^.\\d]).*$", "$2");

It does this by requiring that the preceding and following chars of the group are neither a dot nor a digit (and covers the edge case of start/end of input).

The added special sauce of returning blank for no match if achieved by adding ? to the captured group, allowing it to be absent (thus capturing nothing), yet allowing the whole expression to still match the entire input, thus returning nothing.


Here's some test code:

for (String str : new String[] {"234 587.094", "234",  "xxx", "foo 587.094"})
    System.out.println(str.replaceAll(".*?(^|[^.\\d])(\\d+)?($|[^.\\d]).*$", "$2"));

Output:

234
234
<blank>
<blank>

Upvotes: 1

Arunesh Singh
Arunesh Singh

Reputation: 3535

First split your String with 1 or more spaces \s+ and store in array of strings then filter out the

values which does not contains a ".". Try this:

String str = "234 587.094";
String[] array = str.split("\\s+");

for(int i = 0; i < array.length; i++)
{
    if(!array[i].contains(".")){
    System.out.println(array[i]);
    }
}

Upvotes: 1

Related Questions