简体   繁体   English

如何编写涵盖特定单词的大小写字母的正则表达式?

[英]How to write regular expression that covers small and capital letters of a specific word?

I am trying to use regular expression to find a specific word (with small or capital letters) in a text.我正在尝试使用正则表达式在文本中查找特定单词(小写字母或大写字母)。

Examples are:例子是:

  • none没有任何
  • None没有任何
  • NONE没有任何

However, the following code doesn't find the pattern in sample texts.但是,以下代码未在示例文本中找到该模式。

import re

txt_list = ["None" , "none", "[none]", "(NONE", "Hi"]
pattern = "/\bnone\b/i"


for txt in txt_list:
    if re.search(pattern, txt):
        print(f'Found {txt}')

What is the cause of the above issue?出现上述问题的原因是什么? Is the "pattern" incorrect? “模式”不正确吗?

Do not use slashes to delimit the regular expression.不要使用斜杠来分隔正则表达式。 The syntax in Python is different. Python 中的语法不同。 You can use (?i) to ignore case.您可以使用(?i)忽略大小写。 (Additionally, escape the backslashes or use raw strings.) (此外,转义反斜杠或使用原始字符串。)

pattern = "(?i)\\bnone\\b"

You can also pass the re.IGNORECASE flag to re.search .您还可以将re.IGNORECASE标志传递给re.search

pattern = r"\bnone\b"
for txt in txt_list:
    if re.search(pattern, txt, re.IGNORECASE):
        print(f'Found {txt}')

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

相关问题 正则表达式匹配3个大写字母后跟一个小写字母后跟3个大写字母? - Regular expression to match 3 capital letters followed by a small letter followed by 3 capital letters? 排除两个连续大写字母的正则表达式 - regular expression to exclude 2 consecutive capital letters 正则表达式只删除大写字母的单词 - regular expression to delete words with capital letters only 如何删除字符串中的一对大小写字母? - How to remove pair of small and capital letters in a string? 如何编写正则表达式来匹配重复模式的一小部分? - how to write a regular expression to match a small part of a repeating pattern? 用于查找包含特定字母子集和这些字母出现频率的单词的正则表达式 - Regular expression to find words containing a subset of specific letters and frequencies of these letters 如何替代小写字母的大写字母串并找出不可替代的 - How to substitute the small letters in a string with capital letters and also to find out no of substitutions 计算字符串中小写和大写字母的函数 - Function to count small and Capital letters in a string 编写一个正则表达式来提取一个遵循模式的单词 - write a regular expression to extract a word that follows a pattern 正则表达式,用于忽略第一组字母或python中对象名称中的单词 - Regular expression for ignoring the First set of letters or a word in a object name in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM