我有以下正则表达式:
(electric|acoustic) (guitar|drums)
我需要匹配:
electric guitar
electric drums
acoustic guitar
acoustic drums
electric
acoustic
guitar
drums
我尝试使用?两组之后,但随后一切都匹配了。谢谢!
编辑:
<script type="text/javascript">
var s = "electric drums";
if(s.match('^(?:electric()|acoustic())? ?(?:guitar()|drums())?(?:\1|\2|\3|\4)$')){
document.write("match");
} else {
document.write("no match"); // returns this
}
</script>
最佳答案
使用像这样的基于前瞻的正则表达式:
(?=.*?(?:electric|acoustic|guitar|drums))^(?:electric|acoustic|) ?(?:guitar|drums|)$
Live Demo
关于javascript - 匹配正则表达式中的第一组,第二组或两者,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13742191/