我有类似字符串的一些变体:
#This is a string
#This is another string (with some info in parentheses)
我希望通过正则表达式运行它们并在第一个捕获组中捕获"#This"
,在第二个捕获组中捕获"a string"
或"another string"
。
注意在第二个字符串中我不想要括号'或其内容。
我尝试了一堆或正则表达式提供以下输出
/#(.*) is (.*)/
:最简单的正则表达式,但不排除括号及其内容
String1 Match1: This
String1 Match2: a string
String2 Match1: This
String2 Match2: another string (with some info in parentheses)
/#(.*) is (.*)\(/
添加左括号仅适用于实际拥有它的字符串
String1 Match1: null
String1 Match2: null
String2 Match1: This
String2 Match2: another string
/#(.*) is (.*)\(*/
使其*
可选(我猜错了)
String1 Match1: This
String1 Match2: a string
String2 Match1: This
String2 Match2: another string (with some info in parentheses)
/#(.*) is (.*)\(?/
使?
(相同结果)
String1 Match1: This
String1 Match2: a string
String2 Match1: This
String2 Match2: another string (with some info in parentheses)
/#(.*) is (.*?)\(*/
让它变得非贪婪
String1 Match1: This
String1 Match2: null
String2 Match1: This
String2 Match2: null
var string1 = "#This is a string";
var string2 = "#This is another string (with some info in parentheses)";
// var regex = /#(.*) is (.*)/;
// var regex = /#(.*) is (.*)\(/;
// var regex = /#(.*) is (.*)\(*/;
var regex = /#(.*) is (.*)\(?/;
// var regex = /#(.*) is (.*?)\(*/;
var match1 = string1.match(regex);
var match2 = string2.match(regex);
alert('String1 Match1: \t' + ((match1&&match1[1])?match1[1]:'null') + '\nString1 Match2: \t' + ((match1&&match1[2])?match1[2]:'null') +
'\nString2 Match1: \t' + ((match2&&match2[1])?match2[1]:'null') + '\nString2 Match2: \t' + ((match2&&match2[2])?match2[2]:'null') );