我有一些类似字符串的变体:
#This is a string
#This is another string (with some info in parentheses)
我想通过正则表达式运行它们并在第一个捕获组中捕获“#This”
,以及“一个字符串”
或“另一个字符串"
在第二个捕获组中。
请注意,在第二个字符串中,我不需要括号或其内容。
我尝试了一堆给出以下输出的正则表达式
/#(.*) 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
/#(.*) 是 (.*)\(*/
使其成为可选的 *
(我猜这是不正确的)
String1 Match1: This
String1 Match2: a string
String2 Match1: This
String2 Match2: another string (with some info in parentheses)
/#(.*) 是 (.*)\(?/
使其成为可选的 ?
(相同的结果)
String1 Match1: This
String1 Match2: a string
String2 Match1: This
String2 Match2: another string (with some info in parentheses)
/#(.*) 是 (.*?)\(*/
使其非贪婪
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') );
最佳答案
要使任何符号或组(包括)左括号可选,您需要使用 ? (问号),而不是*(星号)。
您需要停在 ( 或首先出现的行尾,所以也许您需要像 /#(.*) is (.*?)(\(|$)/m
关于javascript - 正则表达式:排除捕获可能存在或不存在的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054506/