简体   繁体   English

正则表达式匹配子字符串,但不以某些字符开头

[英]regex to match a substring, but not starting with certain characters

I am searching for a substring eg test , in a longer string eg alongstringtest .我正在搜索一个子字符串,例如test ,在一个更长的字符串中,例如alongstringtest

In this example it would match ok在这个例子中它会匹配 ok

but I want to exclude certain cases ( when 'test' preceded by certain characters)但我想排除某些情况(当 'test' 前面有某些字符时)

eg例如

do not match 'a-test' (because of '-' )不匹配 'a-test' (因为 '-' )

do not match 'abcgtest' (because of 'g' )不匹配 'abcgtest' (因为 'g' )

do not match 'abc"test' (because of '"' )不匹配 'abc"test' (因为 '"' )

I haven't written any regex for a long time, so this has me pulling my hair out abit !我已经很久没有写任何正则表达式了,所以这让我有点头疼!

使用负面回顾

(?<![-g"])test

The simplest answer is最简单的答案是

/(?<![g"-])test/

But there is room for optimization if you need more performance.但是如果您需要更高的性能,还有优化的空间。 If test can't appear at the very start of the string, then the following is a clear winner in terms of simplicity and performance:如果test不能出现在字符串的最开头,那么就简单性和性能而言,以下显然是赢家:

/[^g"-]test/

Otherwise, I'd try the following:否则,我会尝试以下操作:

/test(?<![g"-].{4})/s

/^test|[^g"-]test/

/^test/ || /[^g"-]test/

Note: - can have special meaning in character classes, but not if it's the first character, the first character after the negating ^ , or the last character.注意: -在字符类中可以具有特殊含义,但如果它是第一个字符、否定^之后的第一个字符或最后一个字符,则不是。 I always use it last;我总是最后使用它; it keeps things nice and simple.它使事情变得美好而简单。

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

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