Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在多个正则表达式中重用公共模式?_Javascript_Regex_Dry - Fatal编程技术网

Javascript 如何在多个正则表达式中重用公共模式?

Javascript 如何在多个正则表达式中重用公共模式?,javascript,regex,dry,Javascript,Regex,Dry,是否可以只编写一次BCC Fans community来编写此类指令 if (document.title.match(/(.+?) - BCC Fans community$/)) { document.title = document.title.match(/(.+?) - BCC Fans community$/)[1] } else if (document.title.match(/^BCC Fans community - (.+)/)) { document.ti

是否可以只编写一次BCC Fans community来编写此类指令

if (document.title.match(/(.+?) - BCC Fans community$/)) {
    document.title = document.title.match(/(.+?) - BCC Fans community$/)[1]
} else if (document.title.match(/^BCC Fans community - (.+)/)) {
    document.title = document.title.match(^/BCC Fans community - (.+)/)[1]
}

将它们写为字符串,然后使用new
RegExp(\u string\u)请参见

只要将正则表达式组合到
^BCC Fans community-(.+)|(.+?)-BCC Fans community$
中,然后您的结果就是
m[1]| m[2]
如果
m
@ctwheels,除了Eric的答案之外,这很有用。非常感谢。