找到一个带正则表达式的模式

时间:2013-08-21 09:04:24

标签: javascript jquery regex

我必须使用Regex找到带有“app”的字符串。模式必须与此类似

有效示例

test app 
test-app 
test app 2 
test app 3 until test app x 
test-app-beta

无效的例子

app test 
application test 
app 2 test 
app-betaxx
你可以帮我吗?

2 个答案:

答案 0 :(得分:1)

这将匹配列出的所有测试用例。

var tests = ['test app', 
             'test-app', 
             'test app 2', 
             'test app 3 until test app x', 
             'test-app-beta', 
             'app test', 
             'application test', 
             'app 2 test', 
             'app-betaxx'];

// match any string that contains but doesnt start with "app"
var regexp = /.{1,}app.*/;

var testsLen = tests.length;
while (--testsLen) {

  var testee = tests[testsLen];
  var result = regexp.exec(testee);

  if (result) {
    console.log('match: ', result[0]);
  } else {
    console.log('no match: ', testee);
  }

}

输出:

Results

答案 1 :(得分:0)

那么,“app”必须在前面有空格或短划线?

以下解决方案做出了这样的假设。

/((?:\s|-)app)/

Image http://f.cl.ly/items/1y0b3F3B1x0Z0b2A0Z1z/orreMBA%202013-08-21%20kl.%2011.10.32.PNG

来自Regexper的图片