首页 > 解决方案 > 正则表达式检查它是否恰好是一个单词

问题描述

我基本上是在尝试匹配字符串模式(通配符匹配)请仔细看看这个 -

*(star) - 正好是一个词。

这不是正则表达式模式......这是一个约定。

所以,如果有这样的模式 -

*.key - '.key.' is preceded by exactly one word(word containing no dots)
*.key.* - '.key.' is preceded and succeeded by exactly one word having no dots
key.* - '.key' preceeds exactly one word .

所以,

"door.key" matches "*.key"
"brown.door.key" doesn't match "*.key".
"brown.key.door" matches "*.key.*"
 but "brown.iron.key.door" doesn't match "*.key.*"

所以,当我在模式中遇到“*”时,我用正则表达式替换它,这意味着它恰好是一个词。(a-zA-z0-9_)。谁能帮我在 python 中做到这一点?

标签: pythonregex

解决方案


要将模式转换为正则表达式,首先需要确保每个字符都按字面意思解释,而不是特殊字符。我们可以通过在任何特殊字符\前面插入 a 来做到这一点。re这些字符可以通过sre_parse.SPECIAL_CHARS.

由于您对 有特殊含义*,因此我们不想逃避该含义,而是将其替换为\w+

代码

import sre_parse

def convert_to_regexp(pattern):
    special_characters = set(sre_parse.SPECIAL_CHARS)
    special_characters.remove('*')

    safe_pattern = ''.join(['\\' + c if c in special_characters else c for c in pattern ])

    return safe_pattern.replace('*', '\\w+')

例子

import re

pattern = '*.key'
r_pattern = convert_to_regexp(pattern) # '\\w+\\.key'

re.match(r_pattern, 'door.key') # Match
re.match(r_pattern, 'brown.door.key') # None

这是一个带有转义特殊字符的示例

pattern = '*.(key)'
r_pattern = convert_to_regexp(pattern) # '\\w+\\.\\(key\\)'

re.match(r_pattern, 'door.(key)') # Match
re.match(r_pattern, 'brown.door.(key)') # None

边注

如果您打算使用re.searchor查找输出模式re.findall,您可能希望将re模式包装在\b边界字符之间。


推荐阅读