[英]JavaScript regex match anything except a letter
我需要匹配“测试”之后的特定字符串
像这样
testing rest -> matches (rest)
testing what -> matches (what)
testing Loong -> matches (Loong)
testing N -> matches (N)
testing L -> this is not matched
testing LL -> matches (LL)
testing J -> matches (J)
testing -> this is not matched
testing -> this is not matched
testing L TY -> this specific string will not occur so it is irrelevant
并带有引号
"testing rest" -> matches (rest)
"testing what" -> matches (what)
"testing Loong" -> matches (Loong)
"testing N" -> matches (N)
"testing L" -> this is not matched
"testing LL" -> matches (LL)
"testing J" -> matches (J)
"testing" -> this is not matched
"testing "-> this is not matched
"testing L TY" -> this specific string will not occur so it is irrelevant
我该怎么办?
应该这样做:
/^testing ([^L]|..+)$/
或者,如果您不能在匹配之前删除引号:
/^"?testing ([^L"]|.[^"]+)"?$/
说明:
第一部分: ^ testing搜索字符串的常量元素-这很容易。
然后,有一个原子组 (在圆括号中): [^ L] | .. + ,它由OR语句(一个管道)组成。
在该OR的左侧,我们为所有一个字符串(字母“ L ”除外)提供了搜索模式。 它是通过定义set(使用方括号[] )和取反(使用此符号^ ,即在方括号中的第一个符号表示否定)来完成的。
在右侧,我们可以搜索长度至少为两个字符的任何内容。 这是通过fisrt匹配所有内容(使用点。 ),然后再匹配任何内容(至少一次)(使用加号: + )来完成的。
总结一下,我们应该完全得到您所要求的逻辑。
如果在字符串末尾前加上“ L
和0+空格,则“基于测试”的正则表达式会导致匹配失败:
/^"?testing\s+((?!L?\s*"?\s*$).*?)"?$/
详细资料 :
^
-字符串开头 "?
-可选的"
testing
-文字字符串testing
\\s+
-1个或多个空格 ((?!L?\\s*"?\\s*$).*?)
-组1捕获除换行符以外的任何0+字符,并且尽可能少(由于懒惰的*?
以解决尾随的"
以后),但只有当不等于L
(1或零次)或空格,接着与字符串的结尾( $
)和\\s*"?\\s*
也将占到可选尾随"
"?
-可选的"
$
-字符串结尾。 因此,如果(?!L?\\s*$)
后面跟有(?!L?\\s*$)
否定超前查询,将使匹配失败:
L
L
和空格... 和可选"
。
var ss = [ '"testing rest"', '"testing what"', '"testing Loong"', '"testing N"', '"testing L"', '"testing"', '"testing "' ]; // Test strings var rx = /^"?testing\\s+((?!L?\\s*"?\\s*$).*?)"?$/; for (var s = 0; s < ss.length; s++) { // Demo document.body.innerHTML += "Testing \\"<i>" + ss[s] + "</i>\\"... "; document.body.innerHTML += "Matched: <b>" + ((m = ss[s].match(rx)) ? m[1] : "NONE") + "</b><br/>"; }
而且,如果您只是想避免在最后将“测试”字符串与L
匹配(在可选的"
之前"
),则可以将模式缩短为
/^"?testing\s((?!L?"?$).*?)"?$/
这是您想要的正则表达式。 它匹配从测试开始的字符串,然后是一个或多个空格字符,然后是至少2个或更多大小的单词字符。
/^testing\s+\w{2,}/
我相信这是您要查找的正则表达式:
/^"(testing(?: )?.*)"$/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.