php 如何匹配正则表达式中的两个单词之一?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1188529/
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
How do you match one of two words in a regular expression?
提问by Adrian Sarli
I want to match either @ or 'at' in a regex. Can someone help? I tried using the ? operator, giving me /@?(at)?/ but that didn't work
我想在正则表达式中匹配 @ 或 'at'。有人可以帮忙吗?我尝试使用 ? 运营商,给我 /@?(at)?/ 但这没有用
回答by Michael Myers
Try:
尝试:
/(@|at)/
This means either @or atbut not both. It's also captured in a group, so you can later access the exact match through a backreference if you want to.
这意味着要么@或at但不是两者兼而有之。它还在一个组中捕获,因此您可以稍后通过反向引用访问完全匹配项(如果需要)。
回答by chaos
/(?:@|at)/
mmyers' answer will perform a paren capture; mine won't. Which you should use depends on whether you want the paren capture.
mmyers 的回答将执行括号捕获;我的不会。您应该使用哪个取决于您是否想要括号捕获。
回答by ghostdog74
if that's only 2 things you want to capture, no need regex
如果这只是您想要捕获的两件事,则不需要正则表达式
if ( strpos($string,"@")!==FALSE || strpos($string,"at") !==FALSE ) {
# do your thing
}
回答by Josh E
have you tried
你有没有尝试过
@|at
that works for (in the .NET regex flavor) the following text
适用于(在 .NET regex 风格中)以下文本
[email protected] johnsmithatgmail.com
[email protected] johnsmithatgmail.com
回答by Erick Asto Oblitas
What about:
关于什么:
^(\w*(@|at))
For:
为了:
- johnsmith@gmail.com
- johnsmithatgmail.com
- jonsmith@atgmail.com
- 约翰史密斯@gmail.com
- johnsmithatgmail.com
- jonsmith @atgmail.com

