简单的正则表达式问题。我有一个字符串的以下格式:
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
注意:在我的用例中,括号不能嵌套。
当前回答
蒂姆·皮茨克的答案在这里
(?<=\[)[^]]+(?=\])
几乎就是我一直在找的人但有一个问题是,一些传统浏览器可能会在正向向后查找时失败。 所以我今天只能靠自己了:)。我设法写下了这些:
/([^[]+(?=]))/g
也许它会帮助别人。
Console.log("这是一个带有[一些]特殊单词的[示例]字符串。(一)“.match (/([^[]+(?=]))/ g));
其他回答
这应该是正确的:
\[([^]]+)\]
这段代码将提取方括号和圆括号之间的内容
(?:(?<=\().+?(?=\))|(?<=\[).+?(?=\]))
(?: 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
括号可以嵌套吗?
如果不是:\[([^]]+)\]匹配一个项目,包括方括号。反向引用\1将包含要匹配的项。如果你的正则表达式口味支持搜索,请使用
(?<=\[)[^]]+(?=\])
这将只匹配括号内的项。
以防万一,你可能有不平衡的括号,你可能会设计一些递归的表达式,
\[(([^\]\[]+)|(?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}`); }); }
源
匹配平衡括号的正则表达式
如果有人想匹配并选择一个在方括号内包含一个或多个圆点的字符串,如“[fu.]”。Bar]"使用以下语句:
(?<=\[)(\w+\.\w+.*?)(?=\])
正则表达式测试器