2016-09-27 8 views
-1

我需要“测试”后到来的特定字符串匹配JavaScript的正则表达式匹配任何

  • 前提是有一个(所以避免匹配“测试”独)
  • ,避免比赛如果该字符串是专门字母 “L”

像这样

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 

我该怎么做?

+0

也许['/ ^“?testing(。{2,}?)”?$ /'](https://regex101.com/r/wI8cY2/2)? –

+0

好吧,也许['/ ^“?testing((?!\ s * L?\ s * $)。*?)”?$ /'](https://regex101.com/r/wI8cY2/3) ? –

+0

'/ ^“(testing(?:)?。*)”$ /' - https://regex101.com/r/cW1dK1/2 – ThePerplexedOne

回答

1

这应做到:

/^testing ([^L]|..+)$/ 

,或者,如果您不能删除引号匹配前:

/^"?testing ([^L"]|.[^"]+)"?$/ 

释:

第一部分:^测试搜索你的字符串常量元素 - 这是容易的部分。

然后,有atomic group(在圆形括号中):[^ L] | .. +它由OR声明(配管)的。

在此的左侧,我们对所有一个字符串搜索模式(除了字母“大号”)。这是做定义集(使用方括号[])和否定(使用此符号:^,这意味着否定时,它是第一个签名方括号)。

在右侧,我们搜索任何至少有两个字符长度的模式。这是通过任何匹配任何东西(使用点号.)并且然后再次执行任何操作来完成的,这次至少一次(通过使用加号:+)。

总结这一点,我们应该得到你所要求的逻辑类型。

+0

“测试生菜”不会匹配 – Gerard

+0

更正的答案,谢谢。 –

+0

但是现在“测试L”将匹配 – Gerard

0

这是你想要的正则表达式。它匹配字符串从测试开始,然后匹配一个或多个空格字符,然后字符大小为2或更大的字符。

/^testing\s+\w{2,}/ 
+0

我并不是想要匹配2个或更多字母的字符串,我的意思是避免匹配特定的字母L(现在在问题中已澄清) – Gerard

1

我建议在先行基于正则表达式,如果“测试”是字符串结束前,随后与L和0+空格失败的比赛:

/^"?testing\s+((?!L?\s*"?\s*$).*?)"?$/ 

regex demo

详细

  • ^ - 字符串的开头
  • "? - 任选"
  • testing - 文字字符串testing
  • \s+ - 1以上空格
  • ((?!L?\s*"?\s*$).*?) - 第1组捕获比换行符符号尽可能少(其他任何0+字符由于懒惰*?,以考虑所述后"以后),但是仅当不等于L(1或零次)或空格,随后用绳子($的端部)和\s*"?\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?"?$).*?)"?$/ 

请参阅this regex demo\s由演示中的空格替代,因为测试是针对多行字符串执行的)

+0

我在前面加了'?\ s *',现在它在最后应该考虑可选的''''。 –

+1

考虑到在我的特殊情况下空间不是可选的,这个简化版本也可以工作^“?testing((?!L?”?$)。*?)“?$所以非常感谢,需要一段时间理解它:) – Gerard

+0

然而,@TZ的答案也有效,我们会同意,它明确地写和理解... – Gerard