Alex Lowe
Alex Lowe

Reputation: 871

How to ignore last occurrence of character?

I have a regular expression that looks like this:

/([A-z0-9]+\-)+/g

It matches the pattern test-string- out of test-string-5RtA. How can I ignore that last - character (but only the last one) out of that match. I tried using a positive lookahead but that doesn't seem to do anything. How can I modify my regular expression to exclude the last - character?

Here is the link to see the regular expression in action.

Upvotes: 3

Views: 1319

Answers (2)

ICloneable
ICloneable

Reputation: 633

A Lookahead should work fine for this purpose if you use it correctly. Try something like this:

^[A-z0-9-]+(?=-)

Because + is greedy, it will match as many - characters as possible (except for the last one because of the Lookahead).

Demo.

Note: I added ^ to make sure the match starts at the beginning of the string. You may remove it if your string might not start with an alphanumeric character and you still consider it as a valid match.


If you want to make sure that - always comes after one or more alphanumeric characters (i.e., no consecutive -), you may use something like this instead:

^(?:[A-z0-9]+-?)+(?=-)

Demo.

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110675

You can use the following regular expression to match strings that contain the specified characters but do not end with a hyphen.

[A-z0-9+\-]+(?<!-)

PCRE Demo

There seems to be no need for a capture group.

(?<!-) is a negative lookbehind. After [A-z0-9+\-]+ has matched "c-at-" in the string "c-at-*", for example, the regex's internal string pointer would be located between the second hyphen and the star. The negative lookbehind, which asserts that the previous character cannot be a hyphen, would then fail. The regex engine would then backtrack one character (to between "t" and "-"), at which point the negative lookbehind would be satisfied, resulting in "c-at" being matched.

Upvotes: 1

Related Questions