在Python中使用正则表达式搜索数字+”

2024-05-23 23:03:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python编译一个正则表达式来搜索这些值values_list = ['4.7"', '5.1"', '5.5"']。你知道吗

此代码根本找不到5.1英寸:

regex = re.compile(r'\b(' + '5.1"' + r')\b')

regex.findall('5.1"')


Tags: 代码relistregexvaluescompile英寸findall
1条回答
网友
1楼 · 发布于 2024-05-23 23:03:04

最后一个单词边界\b是导致正则表达式匹配失败的原因。将图案修改为:

regex = re.compile(r'\b(' + '5.1"' + r')')

会有用的。你知道吗

docs

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

密切注意第二个要点。你知道吗

相关问题 更多 >