繁体   English   中英

正则表达式以首字母开头并且包含一个单词

[英]Regex to with a starting letter AND it contains a word

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";

对于这些字符串,需要找到一个类似的reg,它应该匹配以“ I”开头且包含“一个”或“两个”的字符串

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

但是如何将AND与AND结合使用?

因此str1.test(regx)应该为false。

只要匹配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

在这里测试

不同的方法...

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)

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

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

演示

暂无
暂无

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

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