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"))
Line Anchors In regex, anchors are not used to match characters. Rather they match a position i.e. before, after, or between characters. To match start and end of line, we use following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string. 2.
Javascript regex to match a string that ends with some characters but not with a particular combination of those - Stack Overflow 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.
Use match () for retrieving all matches when using the g global flag. Regex or Regular expressions are patterns used for matching the character combinations in strings. Regex are objects in JavaScript. Patterns are used with RegEx exec and test methods, and the match, replace, search, and split methods of String.
So if regex is all about finding patterns in strings, you might be asking yourself what makes the .match () method so useful? Unlike the .test () method which just returns true or false, .match () will actually return the match against the string you're testing.
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$)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With