简单的正则表达式问题。我有一个字符串的以下格式:
this is a [sample] string with [some] special words. [another one]
提取方括号内的单词的正则表达式是什么?
sample
some
another one
注意:在我的用例中,括号不能嵌套。
简单的正则表达式问题。我有一个字符串的以下格式:
this is a [sample] string with [some] special words. [another one]
提取方括号内的单词的正则表达式是什么?
sample
some
another one
注意:在我的用例中,括号不能嵌套。
当前回答
以防万一,你可能有不平衡的括号,你可能会设计一些递归的表达式,
\[(([^\]\[]+)|(?R))*+\]
当然,这与你可能使用的语言或RegEx引擎有关。
RegEx演示1
除此之外,
\[([^\]\[\r\n]*)\]
RegEx演示2
or,
(?<=\[)[^\]\[\r\n]*(?=\])
RegEx演示3
都是很好的选择。
如果您希望简化/修改/探索表达式,regex101.com的右上方面板中有解释。如果你愿意,你也可以在这个链接中观看,它是如何与一些样本输入匹配的。
RegEx电路
jex。Im可视化正则表达式:
Test
const regex = /\[([^\]\[\r\n]*)\]/gm; const str = `This is a [sample] string with [some] special words. [another one] This is a [sample string with [some special words. [another one This is a [sample[sample]] string with [[some][some]] special words. [[another one]]`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); }
源
匹配平衡括号的正则表达式
其他回答
如果你想要填充方括号a-z之间的小字母
(\[[a-z]*\])
如果你想要小写字母a-zA-Z
(\[[a-zA-Z]*\])
如果你想要小写字母和数字字母a-zA-Z0-9
(\[[a-zA-Z0-9]*\])
如果你想要所有在方括号之间的东西
如果你想要文字,数字和符号
(\[.*\])
如果有人想匹配并选择一个在方括号内包含一个或多个圆点的字符串,如“[fu.]”。Bar]"使用以下语句:
(?<=\[)(\w+\.\w+.*?)(?=\])
正则表达式测试器
如果你不想在匹配中包含括号,下面是正则表达式:(?<=\[).*?(?=\])
让我们来分析一下
的。匹配除行结束符以外的任何字符。?=是一个正面的前瞻。当某个字符串跟在某个字符串后面时,正向向前查找该字符串。<=是一个正向的后视。当某个字符串位于某个字符串的前面时,正向向后查找查找该字符串。引用一下,
积极地向前看(?=) 在表达式B后面找到表达式A: (? = B) 正面看后面(?<=) 在表达式B中找到表达式A 之前: (? < = B)
另一种选择
如果您的正则表达式引擎不支持头视和后视,那么您可以使用正则表达式\[(.*?)\]来捕获组中括号的内部结构,然后您可以根据需要操作组。
这个正则表达式是如何工作的?
括号捕获组中的字符。. * ?以非贪婪的方式获取括号之间的所有字符(行结束符除外,除非启用了s标志)。
以防万一,你可能有不平衡的括号,你可能会设计一些递归的表达式,
\[(([^\]\[]+)|(?R))*+\]
当然,这与你可能使用的语言或RegEx引擎有关。
RegEx演示1
除此之外,
\[([^\]\[\r\n]*)\]
RegEx演示2
or,
(?<=\[)[^\]\[\r\n]*(?=\])
RegEx演示3
都是很好的选择。
如果您希望简化/修改/探索表达式,regex101.com的右上方面板中有解释。如果你愿意,你也可以在这个链接中观看,它是如何与一些样本输入匹配的。
RegEx电路
jex。Im可视化正则表达式:
Test
const regex = /\[([^\]\[\r\n]*)\]/gm; const str = `This is a [sample] string with [some] special words. [another one] This is a [sample string with [some special words. [another one This is a [sample[sample]] string with [[some][some]] special words. [[another one]]`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); }
源
匹配平衡括号的正则表达式
这段代码将提取方括号和圆括号之间的内容
(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\]))
(?: non capturing group
(?<=\().+?(?=\)) positive lookbehind and lookahead to extract the text between parentheses
| or
(?<=\[).+?(?=\]) positive lookbehind and lookahead to extract the text between square brackets