halaldin
halaldin

Reputation: 53

String filter ignoring regular expressions

I want to filter a list of Strings but ignoring regular expressions. For example: Looking for "test.xy" should only show entries like "test.xy" or "abctest.xy" but not "testaxy". I dont want "." working as a wild card.

How can I do that?

Upvotes: 0

Views: 107

Answers (2)

WJS
WJS

Reputation: 40072

If you want to filter the strings and collect them in a new list you can do it as follows;

    List<String> strings = List.of("mytest.xy",
            "abctest.xy", "test.xy", "testaxy", "testy");
    String target = "test.xy";
    List<String> result = strings.stream()
            .filter(str -> str.contains(target))
            .collect(Collectors.toList());

    result.forEach(System.out::println);

Prints

mytest.xy
abctest.xy
test.xy

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79435

Given below is an example:

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

public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("test.xy", "abctest.xy", "testaxy", "testy");
        for (String s : list) {
            if (s.contains("test.xy"))
                System.out.println(s);
        }

        // Display using Stream
        System.out.println("\nFilter and display using Stream:");
        list.stream().filter(s -> s.contains("test.xy")).forEach(System.out::println);
    }
}

Output:

test.xy
abctest.xy

Filter and display using Stream:
test.xy
abctest.xy

Upvotes: 1

Related Questions