首先,我检查了以前的这些帖子,但没有帮助我。1 & 2 & 3.
我有这个字符串(或者类似的情况),需要用regex来处理:
“文本表6-2:儿童学习和行动的管理”
6 or 6-2 or 66-22 or 66-2
这样做后,返回值必须如下所示:
return 1 and 2 as one string, the rest as another string
e.g. returned value must look like this: Text Table 6-2, Management of children study and actions
下面是我的代码:
mystr = "Text Table 6-2: Management of children study and actions"
if re.match("([a-zA-Z0-9]+[ ])?(figure|list|table|Figure|List|Table)[ ][0-9]([-][0-9]+)?", mystr):
print("True matched")
parts_of_title = re.search("([a-zA-Z0-9]+[ ])?(figure|list|table|Figure|List|Table)[ ][0-9]([-][0-9]+)?", mystr)
print(parts_of_title)
print(" ".join(parts_of_title.group().split()[0:3]), parts_of_title.group().split()[-1])
第一个要求应该返回为真,但第二个要求不返回,我更改了代码并使用了compile
,但是regex
功能发生了变化,代码如下所示:
mystr = "Text Table 6-2: Management of children study and actions"
if re.match("([a-zA-Z0-9]+[ ])?(figure|list|table|Figure|List|Table)[ ][0-9]([-][0-9]+)?", mystr):
print("True matched")
parts_of_title = re.compile("([a-zA-Z0-9]+[ ])?(figure|list|table|Figure|List|Table)[ ][0-9]([-][0-9]+)?").split(mystr)
print(parts_of_title)
输出:
True matched
['', 'Text ', 'Table', '-2', ':\tManagement of children study and actions']
因此,在此基础上,我如何才能做到这一点,并坚持一个干净和可读的代码?为什么使用compile
会改变匹配呢?
发布于 2022-03-18 14:34:18
匹配更改是因为:
.group().split()
,其中.group()
返回一个字符串的完整匹配。re.compile("...").split()
,其中re.compile返回正则表达式对象。在模式中,这个部分将只匹配一个单词[a-zA-Z0-9]+[ ]
,如果这个部分应该在捕获组[0-9]([-][0-9]+)?
中,那么第一个(单个)数字目前并不是捕获组的一部分。
您可以编写模式,编写4个捕获组:
^(.*? )?((?:[Ll]ist|[Tt]able|[Ff]igure))\s+(\d+(?:-\d+)?):\s+(.+)
看一个regex演示。
import re
pattern = r"^(.*? )?((?:[Ll]ist|[Tt]able|[Ff]igure))\s+(\d+(?:-\d+)?):\s+(.+)"
s = "Text Table 6-2: Management of children study and actions"
m = re.match(pattern, s)
if m:
print(m.groups())
输出
('Text ', 'Table', '6-2', 'Management of children study and actions')
如果您希望点1和2作为一个字符串,那么您可以使用2个捕获组代替。
^((?:.*? )?(?:[Ll]ist|[Tt]able|[Ff]igure)\s+\d+(?:-\d+)?):\s+(.+)
输出将是
('Text Table 6-2', 'Management of children study and actions')
发布于 2022-03-18 15:03:30
你已经有了答案,但我想尝试你的问题来训练自己,所以如果你感兴趣的话,我会给你同样的答案:
((?:[a-zA-Z0-9]+)? ?(?:[Ll]ist|[Tt]able|[Ff]igure)).*?((?:[0-9]+\-[0-9]+)|(?<!-)[0-9]+): (.*)
下面是我测试的链接:https://regex101.com/r/7VpPM2/1
https://stackoverflow.com/questions/71528585
复制相似问题