Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  179] [ 1]  / answers: 1 / hits: 55975  / 14 Years ago, thu, april 8, 2010, 12:00:00

Let's say using Javascript, I want to match a string that ends with [abcde]* but not with abc.



So the regex should match xxxa, xxxbc, xxxabd but not xxxabc.



I am utterly confused.



Edit: I have to use regex for some reason, i cannot do something if (str.endsWith(abc))


More From » regex

 Answers
69

The solution is simple: use negative lookahead:



(?!.*abc$)


This asserts that the string doesn't end with abc.



You mentioned that you also need the string to end with [abcde]*, but the * means that it's optional, so xxx matches. I assume you really want [abcde]+, which also simply means that it needs to end with [abcde]. In that case, the assertions are:



(?=.*[abcde]$)(?!.*abc$)


See regular-expressions.info for tutorials on positive and negative lookarounds.






I was reluctant to give the actual Javascript regex since I'm not familiar with the language (though I was confident that the assertions, if supported, would work -- according to regular-expressions.info, Javascript supports positive and negative lookahead). Thanks to Pointy and Alan Moore's comments, I think the proper Javascript regex is this:



var regex = /^(?!.*abc$).*[abcde]$/;


Note that this version (with credit to Alan Moore) no longer needs the positive lookahead. It simply matches .*[abcde]$, but first asserting ^(?!.*abc$).


[#97130] Monday, April 5, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
charisma

Total Points: 1
Total Questions: 99
Total Answers: 117

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;