Java Regex to extract numbers and strings from a string

Viewed 63

I want to extract numbers and strings from a string.

Ex.

"TU111 1998 SUMMER”

"TU-232 SU 1999"

"TU232 1999 SUMMER"

I was able to get it using two patterns Pattern.compile("\\d+") and Pattern.compile("[a-zA-Z]+") Is there a way to get it using one pattern?

The expected outcome should be

1=>TU 2=> 111/232 3=>1998/1999 4=>SUMMER/SU

3 Answers

You can just pipe the two regexes together:

[0-9]+|[a-zA-Z]+

Demo

Try with this.

Pattern pattern = Pattern.compile("((\\d+)|([a-zA-Z]+))");
        Matcher matcher = pattern.matcher("TU111 1998 SUMMER");
        while (matcher.find()) {
            System.out.println(matcher.group());
        }

Hey you have to use 2 regexes [a-zA-Z]+|[0-9]+ and maybe the different code I wrote below might give you a hint.just updating Pattern.compile() and string will be enough.

Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
    List<String> numbers = new ArrayList<String>();
    Matcher m = p.matcher("your string");
    while (m.find()) {  
        numbers.add(m.group());
    }   
    System.out.println(numbers);
Related