简体   繁体   English

JS提取括号外的所有文本

[英]JS extract all text outside the brackets

I need to extract the text outside the square/round brackets.我需要提取方括号/圆括号外的文本。

"WALL COLOR (IS HERE) [SHERWIN-WILLIAMS]"

The expected result is "WALL COLOR" and not "WALL COLOR "预期结果是"WALL COLOR"而不是"WALL COLOR "

I have tried with我试过

"WALL COLOR (IS HERE) [SHERWIN-WILLIAMS]".match(/\[(.*?)\]/)[0]

Whether a [0] is needed to get result as string instead array.是否需要 [0] 来将结果作为字符串而不是数组。

Assuming your brackets are balanced and there is no escaping etc, It will be easier to do it via .replace .假设您的括号是平衡的并且没有转义等,那么通过.replace来做到这一点会更容易。 You may use this .replace method to remove all strings that are [...] and (...) surrounded with optional whitespaces on both sides.您可以使用这个.replace方法来删除所有[...](...)两边用可选空格包围的字符串。

str = str.replace( /\s*(?:\[[^\]]*\]|\([^)]*\))\s*/g, "" )
//=> "WALL COLOR"

RegEx Demo正则表达式演示

RegEx Details:正则表达式详情:

  • \\s* : Match 0 or more whitespace \\s* : 匹配 0 个或多个空格
  • (?: : Start non-capturing group (?: : 启动非捕获组
    • \\[[^\\]]*\\] : Match text that is [...] \\[[^\\]]*\\] :匹配文本是[...]
    • | : OR : 或者
    • \\([^)]*\\) : Match text that is (...) \\([^)]*\\) : 匹配(...)
  • ) : End non-capturing group ) : 结束非捕获组
  • \\s* : Match 0 or more whitespace \\s* : 匹配 0 个或多个空格

PS: If you want to allow escaped brackets in your input ie WALL COLOR (IS \\(escaped\\) HERE) [SHERWIN-\\[WILL\\]IAMS] then use this bit more complex regex: PS:如果你想在你的输入中允许转义括号,即WALL COLOR (IS \\(escaped\\) HERE) [SHERWIN-\\[WILL\\]IAMS]然后使用这个更复杂的正则表达式:

/\s*(?:\[[^\\\]]*(?:\\.[^\\\]]*)*\]|\([^\\)]*(?:\\.[^\\)]*)*\))\s*/g

RegEx Demo 2正则表达式演示 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM