javascript - 正则表达式:排除捕获可能存在或不存在的模式

标签 javascript regex string

我有一些类似字符串的变体:

#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/

相关文章:

javascript - 如何使用 JavaScript 模拟 x86 无符号 32 位整数乘法?

javascript - 使用 clientHeight/clientWidth 的差异使高度等于宽度

regex - Postgres 搜索字符 X 但不是 XX

javascript - 如何在 JavaScript 中将字符串转换为整数?

php - 使用 mb_substr() 管理韩语多字节字符串会产生乱码

c - 为什么我在字符串缓冲区中获得不同的大小?

javascript - 如何去除滚动条

javascript - NativeScript:模态属性未定义

python - 仅从以下输出中过滤 'download_url' 的值 - python

检查选项有效性的正则表达式,不允许重复