【问题标题】:Regex in Python to match words with special charactersPython中的正则表达式来匹配带有特殊字符的单词
【发布时间】:2018-04-17 14:37:32
【问题描述】:

我有这个代码

import re

str1 = "These should be counted as a single-word, b**m !?"
match_pattern = re.findall(r'\w{1,15}', str1)

print(match_pattern)

我希望输出是:

['These', 'should', 'be', 'counted', 'as', 'a', 'single-word', 'b**m']

输出应排除非单词,例如“!?”我应该使用哪些其他验证来匹配并实现所需的输出?

【问题讨论】:

  • 非正则表达式解决方案:str1.strip(string.punctuation).replace(',','').split()

标签: python regex python-3.x


【解决方案1】:

我会使用填充 1 个或多个非空格的单词边界 (\b):

match_pattern = re.findall(r'\b\S+\b', str1)

结果:

['These', 'should', 'be', 'counted', 'as', 'a', 'single-word', 'b**m']

!? 被跳过,这要归功于单词边界魔法,它根本不认为这是一个单词。

【讨论】:

  • \S 也将匹配 !?
  • @tripleee 理论上是的,但它有效。嗯,这是防止这种情况发生的单词边界。
  • 非常感谢@Jean-FrançoisFabre!
【解决方案2】:

您可能想要 [^\s.!?] 而不是 \w 之类的东西,但您到底想要什么并不能从单个示例中看出。 [^...] 匹配不属于括号之间的单个字符,\s 匹配空白字符(空格、制表符、换行符等)。

【讨论】:

    【解决方案3】:

    您也可以不使用 RegEx 获得类似的结果:

    string = "These should be counted as a single-word, b**m !?"
    replacements = ['.',',','?','!']
    
    for replacement in replacements:
        if replacement in string:
            string = string.replace(replacement, "");
    
    print string.split()
    
    >>> ['These', 'should', 'be', 'counted', 'as', 'a', 'single-word', 'b**m']
    

    【讨论】:

    • string.strip(element) 什么都不做。
    最近更新 更多