且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从正则表达式中排除括号中的字符串?

更新时间:2023-02-18 15:15:25

这不是完整的正则表达式,但可以帮助您:

This isn't a full regex, but it'll get you there:

(\([^)]*\)|\S)*

这是一个常见的技巧,将一个长字符串当作一个字符来对待.在右侧,我们将非空格字符与 \ S 匹配.在左侧,我们将一组平衡的括号匹配,中间包含任何括号.

This uses a common trick, treating one long string of characters as if it were a single character. On the right side we match non-whitespace characters with \S. On the left side we match a balanced set of parentheses with anything in between.

最终结果是将一组平衡的括号视为单个字符,因此正则表达式作为一个整体与单个单词匹配,其中一个单词可以包含这些带有括号的组.

The end result is that a balanced set of parentheses is treated as if it were a single character, and so the regex as a whole matches a single word, where a word can contain these parenthesized groups.

(请注意,由于这是一个正则表达式,因此无法处理嵌套括号.一组括号是限制.)

(Note that because this is a regular expression it can't handle nested parentheses. One set of parentheses is the limit.)