Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to find positive & negative numbers + expressions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading