'How to get part of string from regex in Java

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



Solution 1:[1]

Alternative regex:

"(\\d[\\s\\d]*?)-(\\d[\\s\\d]*?)\\sUSD"

Regex in context:

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

    Matcher matcher = Pattern.compile("(\\d[\\s\\d]*?)-(\\d[\\s\\d]*?)\\sUSD").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

Other alternative, Alt. 2:

"\\d[\\s\\d]*?(?=-|\\sUSD)"

Alt. 2 regex in context:

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

    Matcher matcher = Pattern.compile("\\d[\\s\\d]*?(?=-|\\sUSD)").matcher(input);
    List<String> minAndMaxValueList = new ArrayList<>(2) ;
    while (matcher.find()) {
        minAndMaxValueList.add(matcher.group(0));
    }

    System.out.printf("Min value: %s. Max value: %s%n", minAndMaxValueList.get(0), minAndMaxValueList.get(1));
}

Alt. 2 output:

Min value: 5 000. Max value: 10 000

Solution 2:[2]

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);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Hongming Chen