gpt4 book ai didi

Python正则表达式数字或字符串前后的空格

转载 作者:行者123 更新时间:2023-12-01 01:40:18 33 4
gpt4 key购买 nike

我正在学习正则表达式并有以下问题。

我提到了 page并得到以下信息

\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. For example, r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

代码:

import re

abc="A \ncat and a rat"+ "\ncan't be friends."
print (abc)
if re.search(r'\bcat\b',abc):
print ("Found")
else:
print ("not found")

我想找到所有案例我的字符串前后必须有数字或空格。

所以'1cat4' , 'cat' , '1cat ' , ' cat ' , '(cat)'当我搜索 'cat' 时应该返回正数.

我应该如何更新我的代码?

最佳答案

看起来您想要找到任何被非字母字符包围或位于文本开头或结尾的:

abc="cat. A \ncat and a rat\ncan't be friends, how about 1cat23 and concatenate?"
re.findall(r'(?:[^a-zA-Z]|^)(cat)(?:[^a-zA-Z]|$)',abc)
#['cat', 'cat', 'cat']

以下是发现的猫的背景:

re.findall(r'(?:[^a-zA-Z]|^)cat(?:[^a-zA-Z]|$)',abc)
#['cat.', '\ncat ', '1cat2']

不幸的是,这个正则表达式不能识别成群的(“catcat”、“cat cat”等)。如果这是一个问题,您可以向正则表达式添加更多子句。

关于Python正则表达式数字或字符串前后的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51958483/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com