python - 正则表达式检查它是否恰好是一个单词
问题描述
我基本上是在尝试匹配字符串模式(通配符匹配)请仔细看看这个 -
*(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 中做到这一点?
解决方案
要将模式转换为正则表达式,首先需要确保每个字符都按字面意思解释,而不是特殊字符。我们可以通过在任何特殊字符\
前面插入 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.search
or查找输出模式re.findall
,您可能希望将re
模式包装在\b
边界字符之间。
推荐阅读
- go - 提供 http 服务的打开文件过多
- java - Spring Boot 2.xx 与 hibernate 4.3.x 的兼容性问题
- ionic-framework - 带有 Web 组件图像的图像网格布局
- android - 如何解决 recyclerView Android 中的 addInArray 异常和 removeFromArray 异常?
- php - get_permalink(0) 的结果;
- java - 如何在另一个/下一个活动中将微调器选择的值显示为 android 中的微调器本身?
- vue.js - Vuetify v-data-table 不更新分页
- mongodb - 如何处理`MongoException`?
- regex - 从 VS Code 中的正则表达式替换特定字符
- reactjs - 如何在自定义 api 处理程序反应 javascript 类中访问 redux 存储