简体   繁体   English

Python中的正则表达式以匹配带有特殊字符的单词

[英]Regex in Python to match words with special characters

I have this code 我有这个代码

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)

I want the output to be: 我希望输出为:

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

The output should exclude non-words such as the "!?" 输出应排除非单词,例如“!?” what are the other validation should I use to match and achieve the desired output? 我还应该使用其他哪些验证来匹配并实现所需的输出?

I would use word boundaries ( \\b ) filled with 1 or more non-space: 我将使用填充有1个或多个非空格的单词边界( \\b ):

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

result: 结果:

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

!? is skipped thanks to word boundary magic, which don't consider that as a word at all either. 跳过了单词边界魔术,这完全不是单词。

You can also achieve a similar result not using RegEx: 您也可以不使用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']

Probably you want something like [^\\s.!?] instead of \\w but what exactly you want is not evident from a single example. 可能您希望使用类似[^\\s.!?]而不是\\w东西,但是从单个示例中看不出您想要的确切内容。 [^...] matches a single character which is not one of those between the brackets and \\s matches whitespace characters (space, tab, newline, etc). [^...]匹配一个括号内的单个字符,而\\s匹配空白字符(空格,制表符,换行符等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM