【问题标题】:Python Regex to find any word within a string that has a commaPython正则表达式查找字符串中带有逗号的任何单词
【发布时间】:2019-05-16 15:44:24
【问题描述】:

我正在尝试处理一些 SQL 代码以查找 select 语句中需要在查询中进一步分组的部分。例如:

在字符串"Select person, age, name, sum(count distinct arrests) from..."

我希望返回"sum(count",因为它是该字符串中唯一在两边都有空格并包含左括号的部分。

我一直在尝试不同的事情,但我很挣扎。

我已经尝试过 re.compile(r'\W.*[)]') 并且要么得到太多回报,要么什么都没有。

【问题讨论】:

  • 您的标题和问题与您想要的不一致。您能否尝试澄清您的问题并提供您尝试的minimal reproducible example
  • 您是要匹配带有逗号的单词还是两边带有空格的单词?
  • 两边有空格且在该单词中包含“(”作为字符的单词
  • @S420L 我已经为您添加了答案。这对你有帮助吗?

标签: python sql regex


【解决方案1】:

使用模式(\w+\(\w+)\s+

例如:

import re

s = "Select person, age, name, sum(count distinct arrests) from..."
print(re.search(r"(\w+\(\w+)\s+", s).group(1))

输出:

sum(count

【讨论】:

  • 谢谢!这主要是可行的,但是我有一个用例,其中一个词是“COUNT(DISTINCT(case when etc...)”,我希望返回“COUNT(DISTINCT(case”)并且使用此代码我只会得到“DISTINCT( case",它把前面的词去掉了
【解决方案2】:

如果匹配也可以出现在字符串的开头,您可以使用环视来断言左侧和右侧不是非空白字符 \S 并使用重复组 (?:...)+ 进行匹配超过 1 次。

(?<!\S)(?:\w+\(\w+)+(?!\S)

Regex demo

这将匹配 COUNT(DISTINCT(casesum(count

【讨论】:

    【解决方案3】:

    split()list-comprehension非正则表达式方式怎么样

    some_list = "Select person, age, name, sum(count distinct arrests) from...".split(' ')
    matching = [s for s in some_list if "(" in s][0]
    print(matching) # sum(count
    
    
    some_list = "COUNT(DISTINCT(case when etc...)".split(' ')
    matching = [s for s in some_list if "(" in s][0]
    print(matching) # COUNT(DISTINCT(case
    

    工作演示: https://rextester.com/ZKJU83182

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 2017-09-28
      • 2021-10-19
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多