简体   繁体   English

Javascript REGEX:忽略两者之间的任何内容?

[英]Javascript REGEX: Ignore anything in between?

How do I ignore anything in between with Javascript RegEx? 如何忽略Javascript RegEx之间的任何内容?

For example, I want to detect all three words: how are you in that order. 例如,我想检测所有三个字: how are you的顺序。

My regex: 我的正则表达式:

var pattern = /([how]+[are]+[you]+)/i;

pattern.test("howare"); //false <--- expected (correct)
pattern.test("areyou"); //false <--- expected (correct)
pattern.test("howareyou"); //true <--- expected (correct)
pattern.test(" howareyou! "); //true <--- expected (correct)
pattern.test("how are  you"); //false <--- this should match!
pattern.test("how areyou  "); //false <--- this should match!

But then I want to ignore anything in between them. 但是,我想忽略它们之间的任何东西。

You just want to add a wildcard in between your words by using 您只想使用以下命令在单词之间添加通配符

.* // 0 or more of any character

Regex rules are by default greedy, so trying to match are will take precedence over .* . 正则表达式规则默认为贪婪,因此尝试匹配are将优先于.*

To note however you need to take out your square brackets as they'll currently allow things to match that shouldn't. 需要注意的是,您需要将方括号取出,因为它们当前允许匹配的东西不应该匹配。 For example they would allow hooooowareyou to match, as the square brackets allow all of the given characters, and the + indicates 1 or more. 例如,它们将允许hooooowareyou进行匹配,因为方括号允许所有给定字符,而+表示1或更大。

Try something like: 尝试类似:

how.*are.*you

It's unclear if you want all your test cases to pass, if you do then here's an example of this answer in action https://regex101.com/r/aTTU5b/2 尚不清楚您是否希望所有测试用例都通过,如果这样做,那么这里是此答案的一个示例: https://regex101.com/r/aTTU5b/2

You can use this regex: 您可以使用此正则表达式:

how.*?are.*?you

This will ensure that how , are and you are present in the same order and ignore any characters in-between. 这将确保如何 存在于相同的顺序和在两者之间忽略任何字符。 So it will return a match for howwww areee!#%@!$%$#% you? 因此,它将返回对howwww areee!#%@!$%$#% you?的匹配howwww areee!#%@!$%$#% you? etc. Check out more positive and negative cases using the demo link below: 等等。使用下面的演示链接查看更多正面和负面案例:

Demo: https://regex101.com/r/rzhkHC/3 演示: https : //regex101.com/r/rzhkHC/3

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

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