简体   繁体   English

将字符串与正则表达式匹配将返回null

[英]Matching a string with regular expression returns null

I am trying to match a string for two cases by a single regular expressing in JavaScript. 我试图通过单个正则表达式在JavaScript中匹配两种情况的字符串。 The string can be in any one of the given formats 字符串可以是任何给定格式

//Singapore
//Singapore (country)

I have tried the following regular expression to match the strings 我尝试了以下正则表达式来匹配字符串

"singapore".match(/(.*) (?:\((.*)\))?/)
//null
"singapore (country)".match(/(.*) (?:\((.*)\))?/)
//["singapore (country)", "singapore", "country"]

I want both the results to return an array like the 2nd case where the 3rd entry in the array can be undefined/empty or not present at all but the result should not be null. 我希望两个结果都返回一个数组,就像第二种情况一样,其中数组中的第三项可以是未定义/空的或根本不存在,但结果不应为null。

Can this be done by a single regular expression. 可以通过单个正则表达式来完成。 If yes then what is the mistake in the above expression 如果是,那么上面表达式中的错误是什么

您需要将空格放在可选组中,因为在仅"singapore"的情况下不是这样: /^([^\\(]*)(?: \\(([^\\)]*)\\))?$/

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

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