正则表达式到带有起始字母,它包含一个单词

Regex to with a starting letter AND it contains a word

本文关键字:包含一 单词 正则表达式      更新时间:2023-09-26
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 组合两者?

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

只需匹配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).*$/;

演示