Home > Net >  Regex to find positive & negative numbers expressions
Regex to find positive & negative numbers expressions

Time:01-09

I'm looking for regex to find positive & negative numbers any expressions in a text file. Here is what I've currenly done:

public class EquationsTextExtractor implements RegexTextExtractor{
@Override
public List<String> extract(String source) {
    List<String> equations = new ArrayList<>();
    Matcher matcher = Pattern.compile("\\d (\\.\\d )?\\s*[ \\-*/]\\s*\\d (\\.\\d )?").matcher(source);
    while (matcher.find()) {
        equations.add(matcher.group());
    }
    return equations;
}

}

The current output is:

[02-495, 00-120, 2   2]

The desired output is:

 2   2, -5.4 / -3.33

Here is sample text:

This is an example source in which a person with the PESEL number 12345678901 came to a course with a person with the PESEL number 09876543211. This course took place at the address Warszawa 02-495 Orląt Lwowskich street, although originally they wanted to do it at 00-120 Złota 44, but the place ended, at the course they did arithmetic operations, the first example was solving 2   2, but then we moved on to negative numbers and it was -5.4 / -3.33 and it got a little harder.

CodePudding user response:

This regular expression will give you the desired output:

(?<![a-zA-Z])[ -]?(?:0|[1-9]\d*)(?:\.\d )?\s [*/ -]\s [ -]?(?:0|[1-9]\d*)(?:\.\d )?(?![a-zA-Z])

but there will be some scenarios not covered

Note: to obtain this regular expression I started working with your regular expression and changing things to obtain the desired output

  • Related