简体   繁体   中英

Regex to exclude words beginning with hash tag

I am looking for assistance in coming up with a regular expression which will match ticket number words (any number of characters followed by digits) but not ones that begin with #SN- . Any ideas?

Example String:

A string with has ref like #SN-INC0000058 and simple mention like INC0000059.

RegEx Matches: INC0000059

I am currently stuck at this breakdown which is matching the number after '#SN-' rather than excluding the entire word/string. I suspect - is being treated as a word break... any ideas?

/(?!#SN-)([A-Z]+[0-9]+)\b/g

https://www.regexpal.com/?fam=99443

Since Javascript regex doesn't have the lookbehind feature, there's no way to catch what you want with a simple pattern. However, in a replacement context, you can easily handle this using a function as replacement parameter and a pattern that systematically tries to catch the part you don't want:

var result = yourstr.replace(/(#SN-)?\b[A-Z]+[0-9]+\b/g, function(m,g1) {
    return g1 ? m : 'yourreplacement';
});

When the capture group 1 is defined, the function returns the whole match, otherwise it returns the replacement string.

Note that inside the function you can't use the $& or $1..$n placeholders for the whole match or capture groups. You have to use the function parameters to figure them.


Only to be more rigorous, it can also be done without a callback function if you describe all possibilities before your target, but it's a pain to write and it isn't efficient since the pattern starts with an alternation:

var result = yourstring.replace(/(^|[^-]|(?:[^N]|^)-|(?:[^S]|^)N-|(?:^|[^#])SN-)\b[A-Z]+[0-9]+\b/g, '$1yourreplacement');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM