sollniss
sollniss

Reputation: 2005

Match until the first occurence of the last character of a string

I've tried googling this but all I can find is how to match until a known character occurs. In my case I don't know the character beforehand.

I know I can match the last character of a string with (.?)$, and I know that I can match until a character X occurs with (?:(?!X).)*, but how do I combine the two to match until the first occurence and not the matched occurence?

Examples:

character → char
test → t
no match → no match
This is a test → This is a t
I came. I saw. I conquered. → I came.

In pseudocode what I want is basically str.substring(0,str.indexOf(str.lastChar)).

Upvotes: 2

Views: 109

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

^(?=(.)*$).*?\1
^(?=.*(.)$).*?\1

See the regex demo. If you need to match multiline strings, see how How do I match any character across multiple lines in a regular expression?.

Details

  • ^ - start of string
  • (?=(.)*$) - a positive lookahead capturing each char other than line break chars up to the end of string (last one is saved in Group 1)
  • .*? - any 0 or more chars other than line break chars as few as possible
  • \1 - same char as in Group 1.

Upvotes: 1

Related Questions