1

I have a string which can be any string, and I want to single it out if is ends in exactly two "s"

for example, "foo", "foos", "foosss", should all return false but "fooss" and "barss" should return true

The problem is if I use .*s{2} for a string like "foosss", java sees "foos" as the .* and "ss" as the s{2}

And if I use .*?s{2} for "foosss" java will see "foo" as the .* for a bit, which is what I want, but once it checks the rest of the string to see if it matches s{2} and it fails, it iterates to the next try

It's important that the beginning string can contain the letter "s", too. "sometexts" and "sometextsss" should return false but "sometextss" should return true

f1sh
  • 11,489
  • 3
  • 25
  • 51

3 Answers3

1

Simply checking whether (^|[^s])s{2}$ matches part of the string should work. $ asserts that the end of the string has been reached whereas ^ asserts that you're still at the beginning of the string. This is necessary to match just ss preceded by no non-s character.

Luatic
  • 8,513
  • 2
  • 13
  • 34
1

You can use

Boolean result = text.matches(".*(?<!s)s{2}");

String#matches requires a full string match, so there is no need for anchors (\A/^ and $/\z).

The (?<!s) part is a negative lookbehind that fails the match if there is an s char immediately to the left of the current location.

See the regex demo.

However, you do not really need a regex here if you can use Java code:

Boolean result = !text.endsWith("sss") && text.endsWith("ss");

which literally means "if text does not end with sss and text ends with ss" the result is True.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0
.*[^s]ss

How i provided:

public static void main(String[] args) {
    String[] strings = new String[]{"fooss", "barss", "foosss", "foos", "foo", "barssss"};

    for (String s : strings) {
        if (s.matches(".*[^s]ss")) {
            System.out.println(s);
        }
    }
}

Output: fooss barss