简体   繁体   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";

for these string need to find a reg like it should match string starts with "I" AND contains "one" or "two". 对于这些字符串,需要找到一个类似的reg,它应该匹配以“ I”开头且包含“一个”或“两个”的字符串

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

But how to combain both with an AND ? 但是如何将AND与AND结合使用?

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

Just match any character between I and one 只要匹配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 a fiddle to test 在这里测试

different approach ... 不同的方法...

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)

It would be better if you add a word boundary. 如果添加单词边界会更好。

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

DEMO 演示

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

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