簡體   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