Javascript 正则表达式:排除捕获可能存在或不存在的模式
我有一些类似字符串的变体:Javascript 正则表达式:排除捕获可能存在或不存在的模式,javascript,regex,string,Javascript,Regex,String,我有一些类似字符串的变体: #This is a string #This is another string (with some info in parentheses) 我想通过一个正则表达式运行它们,并在第一个捕获组中捕获“#This”,在第二个捕获组中捕获“一个字符串”或“另一个字符串” 注意,在第二个字符串中,我不需要括号或其内容 我尝试了一组或多个正则表达式,它们给出了以下输出 /#(.*)是(.*)/:最简单的正则表达式,但不排除括号及其内容 String1 Match1:
#This is a string
#This is another string (with some info in parentheses)
我想通过一个正则表达式运行它们,并在第一个捕获组中捕获“#This”
,在第二个捕获组中捕获“一个字符串”
或“另一个字符串”
注意,在第二个字符串中,我不需要括号或其内容
我尝试了一组或多个正则表达式,它们给出了以下输出
/#(.*)是(.*)/
:最简单的正则表达式,但不排除括号及其内容
String1 Match1: This
String1 Match2: a string
String2 Match1: This
String2 Match2: another string (with some info in parentheses)
/#(.*)是(.*)\(/
添加左括号只对实际包含它的字符串有效
String1 Match1: null
String1 Match2: null
String2 Match1: This
String2 Match2: another string
/#(.*)是(.*)\(*/
使其成为可选的*
(我想这是不正确的)
/#(.*)是(.*)\(?/
使其与?
一起成为可选的(相同的结果)
/#(.*)是(.*)\(*/
使其不贪婪
String1 Match1: This
String1 Match2: null
String2 Match1: This
String2 Match2: null
var string1=“#这是一个字符串”;
var string2=“#这是另一个字符串(括号中有一些信息)”;
//var regex=/#(.*)是(.*)/;
//var regex=/#(.*)是(.*)\(/);
//var regex=/#(.*)是(.*)\(*/);
var regex=/#(.*)是(.*)\(?/;
//var regex=/#(.*)是(.*)\(*/);
var match1=string1.match(regex);
var match2=string2.match(regex);
警报('String1-Match1:\t'+((Match1和&Match1[1])?Match1[1]:'null')+'\n字符串1-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
的想法,但有一点很好,就是-“#”没有被捕获,或者我遗漏了什么?它不在任何捕获组中。与问题中相同。您可能需要将它包括到第一个组中/(#*)is(.*)(|$)/M只是一个提示:您可以创建不影响结果但用于分组的非捕获组,如“(?:)”另一个解决方案是([^\(\)]*)/(由删除的人发布,但我也喜欢)
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