繁体   English   中英

检测字符串是否包含模式

[英]detect if string contains pattern

如何检测字符串是否包含带有 JavaScript 的模式:

1. input="[Lorem]foo";
2. input="[ ]";
3. input="[ipsum]foo";
4. input="[dolor]foo1";
5. input="[sit  ]foo2";
6. input="[ amet]foo3";
7. input="amet]foo3";
...

脚本应该以这种方式处理input

1. string1='Lorem'; string2="foo";
2. do nothing;
3. string1='ipsum'; string2="foo";
4. string1='dolor'; string2="foo1";
5. do nothing;
6. do nothing;
7. do nothing;
...

这将是脚本的一部分......

input  = "[asd]qwe";
input2 = "qwe";

processit(input);
processit(input2);

function processit(e){

   if(..???..){
      alert(string1);
      alert(string2);
   }
   else {
      return false;
   }

}

感谢您的时间。


编辑:解决方案必须是跨浏览器的

IE7+

Firefox 3.6+

铬 7+...

jsbin代码

此正则表达式应实现结果: /\[([a-zA-Z0-9]+)\]([a-zA-Z0-9]+)/

您可以利用split()如何处理捕获组。

var pieces = str.split(/\[(\w+?)\]/);

您可能会得到一些空字符串值。 您可以使用...删除它们

pieces.filter(function(piece) { return piece; });

js小提琴

您的实际要求尚不清楚,所以我猜。 以下将只允许在方括号内和之后仅包含非空字母数字加下划线的字符串,并尝试匹配整个字符串而不是较长字符串中的多次出现。

var input = "[Lorem]foo";
var string1, string2;
var result = /^\[(\w+)\](\w+)$/i.exec(input);
if (result) {
    string1 = result[1];
    string2 = result[2];
}
alert(string1 + ", " + string2);

暂无
暂无

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

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