python - 带有 re.search() 的原始字符串?

标签 python regex

我正在尝试学习如何使用 Python 正则表达式。我希望以下程序在输入字符串中搜索字符串 'N\S\A'。我读到 ( here ) 如果你想处理 '\' 字符,你必须将字符串设为原始字符串。但是我把 r 放在匹配字符串的前面,它仍然不起作用。 (不管inword是'NSA'还是'N\S\A'...)

import re
inword = input('Enter in text that may or may not be suspicious: ')
print("Inword is:", inword)
mword  = re.search(r'N\S\A',inword)
if mword :
    print('Matched',mword .group())
    #deployDrones();
else:
    print('Not matched')

为什么这不起作用?我该怎么做才能修复它?

最佳答案

你不需要正则表达式。

使用 in 运算符:

>>> inword = 'Hello N\S\A!'
>>> r'N\S\A' in inword
True

如果你真的需要正则表达式,你需要转义\本身,因为\S匹配非空格字符(\A也具有特殊意义):

>>> inword = 'Hello N\S\A!'
>>> re.search(r'N\S\A', inword)
>>> re.search(r'N\\S\\A', inword)
<_sre.SRE_Match object at 0x7f804ea33370>

\S

When the UNICODE flags is not specified, matches any non-whitespace character; this is equivalent to the set [^ \t\n\r\f\v] The LOCALE flag has no extra effect on non-whitespace match. If UNICODE is set, then any character not marked as space in the Unicode character properties database is matched.

\A

Matches only at the start of the string.

来自 Regular expression syntax

关于python - 带有 re.search() 的原始字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18461089/

相关文章:

python - 从嵌套字典中按键提取值

Windows 上的 Python - 如何等待多个子进程?

python - celery (Redis)结果后端不工作

正则表达式匹配后面没有一个字符的单个字符

php - 正则表达式提取链接的一部分(php)

python - 在 for 循环中将小矩形打印到屏幕上。 (pygame)

python - 正则表达式 - 在符号后查找数字

javascript - 如何编写只读取 xls 和 xlsx 格式的 excel 文件的验证函数

javascript - 正则表达式匹配除 anchor 标记一之外的所有电子邮件

regex - Incrontab 不处理 IF 语句