如何匹配方括号内的所有特定字符串

时间:2019-04-05 15:38:27

标签: regex

我正在尝试在方括号内匹配单引号。

我必须匹配整个字符串中[item:]中的所有单引号,以将其删除。

以下是一些情况:

请勿删除以下内容中的引号:

  • “文字”
  • ['文本']

删除以下所有引号:

  • [item:'test']

示例:

  1. [test 'item']应该保持原样。
  2. [item: 'item']成为[item: item]
  3. ['test'][item: first 'test']成为['test'][item: first test]
  4. [item: some 'random' text]成为[item: some random text]
  5. [item: 'test 'text 'random' quote']成为[item: test text random quote]

注意:引号不是成对的。可以是引号的奇数。

2 个答案:

答案 0 :(得分:0)

此正则表达式可以捕获包含方括号的组。然后,您只需要根据所使用的语言删除包含方括号。

\[item:[^\]']*('[^']+')[^]]*]

See live example

答案 1 :(得分:0)

With more samples added, the problem is clearer now.

Just to rephrase the problem, you want to match bracketed expression only that starts with item: and get rid of any of the singlequotes within the bracketed expression.

You can use this regex to match and capture the data in groups excluding any of the single quotes,

(\[item:)|(?!^)\G([^'\n]*)'+

and replace with appropriately captured groups which is \1\2

Explanation:

  • (\[item:) - Start by matching [item: literally and captures it in group1
  • | - Alternation
  • (?!^)\G - Matches end of previous match position
  • ([^'\n]*) - Matches any optional text not containing singlequote or newline and captures it in group2 (you can remove \n though as normally it won't be part of your input text)
  • '+ - Matches one or more singlequotes which get removed as they aren't captured in any group.

Demo