简体   繁体   English

正则表达式排除以井号标签开头的单词

[英]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- . 我正在寻找帮助,以找出一个正则表达式,该表达式将与票证号码单词(任意数量的字符后跟数字)匹配,但不匹配以#SN-开头的单词。 Any ideas? 有任何想法吗?

Example String: 示例字符串:

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

RegEx Matches: INC0000059 正则表达式匹配项: INC0000059

I am currently stuck at this breakdown which is matching the number after '#SN-' rather than excluding the entire word/string. 我目前停留在此细分,该匹配与“#SN-”之后的数字匹配,而不是排除整个单词/字符串。 I suspect - is being treated as a word break... any ideas? 我怀疑-被视为断字...任何想法?

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

https://www.regexpal.com/?fam=99443 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. 由于Javascript正则表达式没有后向功能,因此无法通过简单的模式捕获所需内容。 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. 当定义了捕获组1时,该函数返回整个匹配项,否则返回替换字符串。

Note that inside the function you can't use the $& or $1..$n placeholders for the whole match or capture groups. 请注意,在函数内部,不能将$&$1..$n占位符用于整个匹配或捕获组。 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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