【问题标题】:How to remove words starting with lowercase from a sentence using regex如何使用正则表达式从句子中删除以小写字母开头的单词
【发布时间】:2019-07-02 14:19:49
【问题描述】:

“我正在尝试使用正则表达式删除以小写开头的单词,但没有得到所需的输出。”

我的输入是“适用于该法案并成为其中的一部分 Illiam B GEISSLER”

import re 
text = "apply to this bill and are made a part thereof Illam B GEISSLER"  
result = re.sub(r"\w[a-z]", "", text)  
print(result) 

我得到的输出是“I B GEISSLER” 要求输出为“Illiam B GEISSLER”

【问题讨论】:

    标签: regex python-3.x


    【解决方案1】:

    尝试查找模式\b[a-z]+\s*,并替换为空字符串:

    text = "apply to this bill and are made a part thereof Illam B GEISSLER"  
    result = re.sub(r'\b[a-z]+\s*', "", text).strip()
    print(result)
    

    打印出来:

    Illam B GEISSLER
    

    \b[a-z]+\s* 模式背后的想法是它只匹配两侧被单词边界包围的整个单词。请注意,我们调用 strip 来删除任何剩余的空格。

    另一个微妙的点是该模式删除了每个匹配的小写字母的 RHS 上的所有空格。这是为了让文本保持可读性,例如,一些匹配的单词应该位于一些不匹配的单词之间:

    text = "United States Of a bunch of states called America"  
    result = re.sub(r'\b[a-z]+\s*', "", text).strip()
    print(result)
    

    这正确打印:

    United States Of America
    

    【讨论】:

      【解决方案2】:

      您可以搜索大写的单词 在链接中你可以找到一个例子

      Regex - finding capital words in string

      【讨论】:

        【解决方案3】:

        这个表达式也可能有效:

        \s*\b[a-z][a-z]*
        

        Demo 1

        测试

        import re
        
        regex = r"\s*\b[a-z][a-z]*"
        
        test_str = "apply to this bill and are made a part thereof Illam B GEISSLER apply to this bill and are made a part thereof Illam B GEISSLER"
        
        subst = ""
        
        # You can manually specify the number of replacements by changing the 4th argument
        result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
        
        if result:
            print (result)
        

        或者这个:

        ([A-Z].*?\b\s*)
        

        测试

        import re
        
        regex = r"([A-Z].*?\b\s*)"
        test_str = "apply to this bill and are made a part thereof Illam B GEISSLER apply to this bill and are made a part thereof Illam B GEISSLER"
        print("".join(re.findall(regex, test_str)))
        

        输出

        Illam B GEISSLER Illam B GEISSLER
        

        Demo 2

        【讨论】:

        • \s*\b 中的 \b 是多余的,因为空格和字母之间的接口定义为单词边界。
        【解决方案4】:

        试试这个,

        import re
        text = "apply to this bill and are made a part thereof Illam B GEISSLER"
        result = re.sub(r"(\b[a-z]+)", '', text).strip()
        print(result)
        

        输出

        Illam B GEISSLER
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多