正则表达式用起始字母AND它包含一个单词

时间:2014-09-15 13:46:22

标签: javascript regex

var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str2 = "I dont have any two";

对于这些字符串需要找到一个注册表,它应该匹配字符串以“I”开头并且包含“一个”或“两个”。

var regx = "/^I/";        //this starts with I
var regx = "/(one|two)/";  //this match one or two

但是如何与AND?&/ p>结合起来

所以str1.test(regx)应该是假的。

3 个答案:

答案 0 :(得分:4)

只需匹配Ione

之间的任何字符
var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str3 = "I dont have any two";

var regx = /^I.*(one|two)/

console.log(regx.test(str)) // True
console.log(regx.test(str1)) // False
console.log(regx.test(str2)) // False
console.log(regx.test(str3)) // True

Here一个小小的测试

答案 1 :(得分:2)

不同的方法......

var regx1 = /^I/;        //this starts with I
var regx2 = /(one|two)/;  //this match one or two

// starts with "I" AND contains "one" or "two".
var match = regx1.test(str1) && regx2.test(str1)

答案 2 :(得分:1)

如果添加单词边界会更好。

var regx = /^I.*? (?:one|two)( |\b).*$/;

DEMO