Javascript 正则表达式逻辑和或
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5176384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regexp logic and or
提问by Alexander
I know there are logical operators such as |
"the OR operator" which can be used like this:
我知道有一些逻辑运算符,例如|
“OR 运算符”,可以这样使用:
earth|world
I was wondering how I could check if my string contains earth AND world.
我想知道如何检查我的字符串是否包含地球和世界。
regards, alexander
问候,亚历山大
回答by markijbema
If it contains earth AND world, it contains one after the other, so:
如果它包含地球和世界,那么它一个接一个地包含,所以:
earth.*world|world.*earth
an shorter alternative (using extended regex syntax) would be:
更短的替代方案(使用扩展的正则表达式语法)是:
/(?=.*earth)(?=.*world).*/
But it is not at all like an and
operator. You can only do or
because if only one of the words is included, there is no ordering involved. If you want to have them both, you need to indicate the order.
但它完全不像一个and
操作员。您只能这样做,or
因为如果只包含一个单词,则不涉及排序。如果您想同时拥有它们,则需要指明顺序。
回答by iivel
This question was asked and answered here:
在这里提出并回答了这个问题:
Regular Expressions: Is there an AND operator?
There isn't a direct "and" operator, but you can continue expression testing and ensure the second expression is also a match.
没有直接的“和”运算符,但您可以继续表达式测试并确保第二个表达式也匹配。
回答by Walf
do two tests, if the first fails the second doesn't execute in javascript. e.g.
做两个测试,如果第一个失败,第二个不会在 javascript 中执行。例如
var hasBoth = /earth/i.test(aString) && /world/i.test(aString);
回答by Eissa Saber
you don't need & operator actually | operator does the job
你实际上不需要 & 运算符 | 操作员完成工作
let string = 'world and earth are awesome';
let regex = /world|earth/ig;
let result = string.replace(regex, '...');
console.log(string);
console.log(result);