I would like to match strings that end with bar, for example: foobar or bar. Such regexp could be: /^.*bar$/.
I would also like to exclude strings with the letter u prefixed to bar, for instance, these strings should not match the regular expression: ubar or fooubar. I tried /^.*[^u]?bar$/, but it doesn’t work. How could we fix this?
Simply wrap the whole prefix in parentheses
By doing this you only allow further preceding characters, if there was at least one non-
ucharacter beforebar.Alternatively, if your regex engine supports negative lookbehinds, you could do this:
When this regex reaches the position before
barit looks at the character left of it and tries to match au. If that is not possible, the match continues. If theuwas found the lookbehind will make the pattern fail. This works both if there is a non-ucharacter and if it’s the beginning of the string.As sawa pointed out in a comment, you don’t even need the
^.*if you just want to check whether a string ends inbar:Of course, if you want to include the whole string in the match for some reason (replacement or matching lines using multiline mode) then the
^.*is necessary. Note that in the first regex you cannot leave it out. However you could change it toWhich would also avoid matching the whole string.