Home > OS >  How to get part of string from regex in Java
How to get part of string from regex in Java

Time:05-03

For example, I have string with range of earnings:

5 000-10 000 USD

and i want to extract from that string minimum and maximum value. I prepared regexes, for exalmple for first value:

[0-9| ]*-

And now i do not know how to get that part of string. I tried with pattern and matcher like:

 Pattern pattern = Pattern.compile("\\([A-Z|a-z] ");
            Matcher matcher = pattern.matcher(s);
            String employmentType = matcher.group(0);

But I am getting null

CodePudding user response:

Alternative regex:

"(\\d[^-] )-(\\d.*?)\\s USD"

Regex in context:

public static void main(String[] args) {
    String input = "5 000-10 000 USD";

    Matcher matcher = Pattern.compile("(\\d[^-] )-(\\d.*?)\\s USD").matcher(input);
    if(matcher.find()) {
        String minValue = matcher.group(1);
        String maxValue = matcher.group(2);
        System.out.printf("Min: %s, max: %s%n", minValue, maxValue);
    }
}

Output:

Min: 5 000, max: 10 000

CodePudding user response:

If you want to use space to split the string values , you can try this

Pattern p = Pattern.compile("[\\s] ");
String[] result = p.split(text);
  • Related