这是我的代码:

import re
string = "hello\bworld"
reg = r"\bhello\b"
print(re.findall(reg, string))

输出是:

   ['hello']

But this doesn't make sense to me.
In the official python documentaion \b is described as the worst collision between python's and regex's escape squences:

Python字符串字面量和正则字符串之间最严重的冲突 表达序列.在Python的字符串文字中,\b是退格键 字符,ASCII值8.如果你不使用原始字符串,那么Python 会把\b转换成退格键,你的RE不会像你一样匹配 期望它

在Python中,\b被解释为退格键,所以string将被翻译成101.

print(string)

输出是:

hellworld

While in regular expression \b is interpreted as a word boundary
So searching the pattern r"\bhello\b" in hellworld should theoretically yield 0 matches
Since there isn't any hello surrounded by word boundaries in hellworld

我以为结果是一个空名单

另一种方法是使用以下代码:

import re
string = "hello\bworld"
reg = r"hellw"
print(re.findall(reg, string))

here the 输出是:

[]

Which again doesn't make sense to me since there is a hellw in string string
printing string proves it:

print(string)
hellw

我没看到什么?

推荐答案

退格键不会修改字符串的内容,它只是影响字符串在终端上的打印方式.字符串包含o,后面是退格键.由于o是一个单词字符,退格键是一个非单词字符,所以它们之间有一个单词中断,所以regexp中的\b匹配.

Python相关问答推荐

如何处理嵌套的SON?

列表上值总和最多为K(以O(log n))的最大元素数

如何在msgraph.GraphServiceClient上进行身份验证?

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

将特定列信息移动到当前行下的新行

处理(潜在)不断增长的任务队列的并行/并行方法

_repr_html_实现自定义__getattr_时未显示

如何在Python中并行化以下搜索?

try 将一行连接到Tensorflow中的矩阵

为一个组的每个子组绘制,

需要帮助重新调整python fill_between与数据点

与命令行相比,相同的Python代码在Companyter Notebook中运行速度慢20倍

Geopandas未返回正确的缓冲区(单位:米)

python—telegraph—bot send_voice发送空文件

在numpy数组中寻找楼梯状 struct

使用类型提示进行类型转换

如何在Pandas中用迭代器求一个序列的平均值?

Django更新视图未更新

对于数组中的所有元素,Pandas SELECT行都具有值

对当前的鼹鼠进行编码,并且我的按键获得了注册