gpt4 book ai didi

python - 正则表达式:匹配任意单词前的任意数量的括号

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:27 26 4
gpt4 key购买 nike

我有一堆具有以下形式的字符串,其中 X 表示任意单词

This is a string ((X.address)) test
This is a string ((X address)) test
This is a string (X address) test
This is a string (X.address) test

一旦找到 X.addressX address(包括前面的括号),我想删除字符串的所有内容,产生

This is a string
This is a string
This is a string
This is a string

这是我的出发点:

regex = r"\(X.address"
s = "This is a string ((X.address)) test"
re.split(regex, s)[0]

>> 'This is a string ('

它有效,但我需要对其进行概括,以便它搜索任意词而不是 X 并且它会考虑词前的 1 个或多个括号。

最佳答案

你可以使用

re.sub(r'\s*\(+[^()]*\baddress.*', '', s, flags=re.S)

详情

  • \s* - 0+ 个空格
  • \(+ - 1+ ( 个字符
  • [^()]* - 除了 ()
  • 之外的任何 0+ 个字符
  • \b - 单词边界(address 前面不能有其他字母、数字或下划线)
  • address - 一个词
  • .* - 字符串末尾的任何 0+ 个字符。

参见 Python demo :

import re
strs = [ 'This is a string ((X.address)) test', 'This is a string ((X address)) test', 'This is a string (X address) test', 'This is a string (X.address) test', 'This is a string ((X and Y and Z address)) test' ]
for s in strs:
print(s, '=>', re.sub(r'\s*\(+[^()]*\baddress.*', '', s, flags=re.S))

输出:

This is a string ((X.address)) test => This is a string
This is a string ((X address)) test => This is a string
This is a string (X address) test => This is a string
This is a string (X.address) test => This is a string
This is a string ((X and Y and Z address)) test => This is a string

关于python - 正则表达式:匹配任意单词前的任意数量的括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58950716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com