Java Regular Expression Examples

Java 8 stream and regular expression examples.

Note
Learn the basic regular expression at Wikipedia

1. String.matches(regex)

1.1 This example, check if the string is a number.

JavaRegEx1.java

package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;

public class JavaRegEx1 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        for (String number : numbers) {
		
            if (number.matches("\\d+")) {
                System.out.println(number);		// 1, 20, 333
            }
        }

        // Java 8 stream example
        numbers.stream()
                .filter(x -> x.matches("\\d+"))
                .forEach(System.out::println);

    }
}

Output


1
20
333

1
20
333

2. String.replaceAll(regex, replacement)

2.1 This example replaces all digits with #

JavaRegEx2.java

package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;

public class JavaRegEx2 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        for (String number : numbers) {
            System.out.println(number.replaceAll("\\d", "#"));
        }

        // Java 8 stream example
        numbers.stream()
                .map(x -> x.replaceAll("\\d", "#"))
                .forEach(System.out::println);

    }
}

Output


#
##
A#
###
A#A###

#
##
A#
###
A#A###

3. Pattern and Matcher

3.1 Find all digits from a list of String.

JavaRegEx3.java

package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaRegEx3 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        Pattern pattern = Pattern.compile("\\d+");

        for (String number : numbers) {

            Matcher matcher = pattern.matcher(number);
            while (matcher.find()) {
                System.out.println(matcher.group(0));
            }

        }
	
	}
}

Output


1
20
1
333
2
211

3.2 For Java 8 stream, first we try to convert like this:


	numbers.stream()
		.map(x -> pattern.matcher(x))
		.filter(Matcher::find)          // A2A211, will it loop?
		.map(x -> x.group())
		.forEach(x -> System.out.println(x));

Output, the last 211 is missing?


1
20
1
333
2

The stream can’t loop the .filter to get all the groups, we need a hack with a custom Spliterators

JavaRegEx4.java

package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;

public class JavaRegEx4 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        Pattern pattern = Pattern.compile("\\d+");

        numbers.stream()
                .flatMap(x ->
                        StreamSupport.stream(new MatchItr(pattern.matcher(x)), false))
                .forEach(x -> System.out.println(x));


    }

    final static class MatchItr extends Spliterators.AbstractSpliterator<String> {
        private final Matcher matcher;

        MatchItr(Matcher m) {
            super(m.regionEnd() - m.regionStart(), ORDERED | NONNULL);
            matcher = m;
        }

        public boolean tryAdvance(Consumer<? super String> action) {
            if (!matcher.find()) return false;
            action.accept(matcher.group());
            return true;
        }
    }

}

Output


1
20
1
333
2
211

4. Java 9, Scanner.findAll(regex)

4.1 Java 9, we can use Scanner.findAll(regex) to return a stream of match results that match the provided regex.


	Scanner scan = new Scanner("A2A211");
	List<String> collect = scan
			.findAll("\\d+")
			.map(m -> m.group())
			.collect(Collectors.toList());
	collect.forEach(x -> System.out.println(x));

Output


2
211

Final version, with Java 9.

JavaRegEx5.java

package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class JavaRegEx5 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        Pattern pattern = Pattern.compile("\\d+");

        List<String> collect = numbers.stream()
                .map(x -> new Scanner(x).findAll(pattern)
                        .map(m -> m.group())
                        .collect(Collectors.toList())
                )
                .flatMap(List::stream)
                .collect(Collectors.toList());

        collect.forEach(x -> System.out.println(x));

    }

}

Output


1
20
1
333
2
211

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Sameh Yousufi Recent comment authors
newest oldest most voted
Sameh Yousufi
Guest
Sameh Yousufi

Nice and appreciate