JAVA: Check if a string ends with a certain pattern using REGEX

Viewed 34

I have an array of Strings in Java like :

["stringWithNoSuffix", "secondString", "stringWithSuffix01", "stringWithSuffix99", "stringWithSuffix8notCounted"]

I want to get all the strings in my array that end with "WithSuffix" and a number.

E.g: WithSuffix1, WithSuffix22, WithSuffix09, ... etc

My output then should be :

["stringWithSuffix01", "stringWithSuffix99"]

The String "stringWithSuffix8notCounted" is not counted because it does not end with "WithSuffix" and a number.

I can do this with .contains() or .endsWith() and some conditions but I want to use a regex if possible. I am pretty newbie with Regular Expressions so that's the reason why I am here asking.

1 Answers

Use this regular expression: WithSuffix\d+$

Explanation:

  • the "WithSuffix" is the text you want, nothing special
  • \d means a digit
  • + means 1 or more of the previous thingie, here the \d
  • $ means end of the input

Because \ escapes special characters in Java strings, you must escape it with another \.

import java.util.*;

public class WithSuffix {
    public static void main(String[] args) {
        List<String> inputs = List.of("stringWithNoSuffix", "secondString", "stringWithSuffix01",
            "stringWithSuffix99", "stringWithSuffix8notCounted");
        List<String> filtered = new ArrayList<>();
        for (String i: inputs) {
            if (i.matches(".*WithSuffix\\d+$")) {
                filtered.add(i);
            }
        }
        System.out.println(filtered);
    }
}

Here I added a .* (dot means any character, * means any number) to ignore any text before the "WithSuffix".

Related