RegEx匹配所有内容并包括最后的括号

时间:2022-09-07 20:23:57

I have a string of text like this:

我有一串这样的文字:

Bob Smith (Approve) Request reviewed 4/27/2016 (Bob Smith) Have fun on your vacation!

Bob Smith(Approve)要求评论2016年4月27日(Bob Smith)享受您的假期乐趣!

And I want to use a regular expression to match everything up to and including the last parentheses, which would be this:

我想使用正则表达式来匹配所有内容,包括最后一个括号,这将是:

Bob Smith (Approve) Request reviewed 4/27/2016 (Bob Smith)

Bob Smith(Approve)要求审查2016年4月27日(Bob Smith)

I am eventually going to use this regular expression to replace the text up to and including the last parentheses with nothing, so that only the comment at the end is returned. (It would be easier to match on the part after the last parentheses [see below], but I am using a different approach based on a quirk in the program I'm using.)

我最终将使用此正则表达式将文本替换为最后括号并包括最后一个括号,以便只返回最后的注释。 (在最后一个括号后的部分匹配会更容易[见下文],但我正在使用基于我正在使用的程序中的怪癖的不同方法。)

I found this question on SO that asks about how to find everything after the last forward slash: Regular Expression for getting everything after last slash. The answer is:

我在SO上发现了这个问题,询问如何在最后一个正斜杠之后找到所有内容:正则表达式,用于在最后一次斜杠后获取所有内容。答案是:

([^/]+$)

However, I need to modify that regular expression to find everything UP TO AND INCLUDING the last PARENTHESES. I tried to modify to this:

但是,我需要修改该正则表达式以查找最新的内容并包括最后一个父项。我试着修改为:

(^[^)]+) 

but that finds everything up to but NOT INCLUDING the FIRST parentheses.

但是它找到了一切但不包括第一个括号。

How can I change that to match everything up to and including the last parentheses?

如何更改它以匹配包括最后括号在内的所有内容?

See this RegExr as an example: http://regexr.com/3dahe

请参阅此RegExr示例:http://regexr.com/3dahe

1 个解决方案

#1


2  

I want to use a regular expression to match everything up to and including the last parentheses

我想使用正则表达式来匹配所有内容,包括最后一个括号

You just need greedy dot matching:

你只需要贪心点匹配:

^.*\)\s*

See the regex demo

请参阅正则表达式演示

Use a DOTALL modifier if there are newline symbols in the input.

如果输入中有换行符号,请使用DOTALL修饰符。

Pattern details:

  • ^ - start of string
  • ^ - 字符串的开头

  • .* - any 0+ characters other than a newline up to the last
  • 。* - 除了换行符之外的任何0+字符

  • \) - closing parentheses
  • \) - 结束括号

  • \s* - 0+ whitespaces.
  • \ s * - 0+空格。

#1


2  

I want to use a regular expression to match everything up to and including the last parentheses

我想使用正则表达式来匹配所有内容,包括最后一个括号

You just need greedy dot matching:

你只需要贪心点匹配:

^.*\)\s*

See the regex demo

请参阅正则表达式演示

Use a DOTALL modifier if there are newline symbols in the input.

如果输入中有换行符号,请使用DOTALL修饰符。

Pattern details:

  • ^ - start of string
  • ^ - 字符串的开头

  • .* - any 0+ characters other than a newline up to the last
  • 。* - 除了换行符之外的任何0+字符

  • \) - closing parentheses
  • \) - 结束括号

  • \s* - 0+ whitespaces.
  • \ s * - 0+空格。