Home > OS >  Regular Expressions: How do I single out a chain of characters with a precise length at the end of a
Regular Expressions: How do I single out a chain of characters with a precise length at the end of a

Time:06-20

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related