【问题标题】:Python regex search until specific word and exclude everything behind itPython 正则表达式搜索直到特定单词并排除它后面的所有内容
【发布时间】:2020-08-14 08:08:46
【问题描述】:

我有一个脚本,它总是在字符串中包含 "get the""get"“一二三” 可以变化,就像它也可以是 “十三四十”“六”。在这些变化之后,总会有第二个“get”

我有以下代码:

variable = 'get the ONE TWO THREE get FOUR FIVE'

myVariable = re.compile(r'(?<=get the) .*')
myVariableSearch = myVariable.search(variable)
mySearchGroup = myVariableSearch.group()
print(mySearchGroup) 

#prints ONE TWO THREE get FOUR FIVE

我希望我的脚本排除第二个 "get" 及其后面的所有内容。我想要的结果就是“一二三”

如何排除这个?任何帮助将不胜感激!

【问题讨论】:

  • 使用r'(?&lt;=\bget\sthe\s).*?(?=\s*\bget\b|\Z)'
  • 谢谢,正是我需要的!

标签: python-3.x regex search


【解决方案1】:

你可以使用

\bget\s+the\s+(.*?)(?=\s*\bget\b|$)

请参阅regex demo

详情

  • \bget\s+the\s+ - 整个单词 get,1+ 个空格,the,1+ 个空格
  • (.*?) - 第 1 组:
  • (?=\s*\bget\b|$) - 一个正向前瞻,需要 0+ 个空格,然后是整个单词 get,或紧邻当前位置右侧的字符串结尾。

Python demo

import re
variable = 'get the ONE TWO THREE get FOUR FIVE'
myVariableSearch = re.search(r'\bget\s+the\s+(.*?)(?=\s*\bget\b|$)', variable)
mySearchGroup = ''
if myVariableSearch:
    mySearchGroup = myVariableSearch.group(1)
print(mySearchGroup) 
# => ONE TWO THREE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-21
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2018-07-18
    相关资源
    最近更新 更多