通过正则表达式修复 .bib 文件标题



在.bib文件中准备了我的LaTeX参考书目后,我发现大写存在问题。

根据:此信息,解决方案是为每个标题中的每个单词添加括号(正如我检查的那样,在整个标题中添加括号不起作用)。

例如,我希望

title   = "What a interesting title",
title= "What a boring title",
title="What a crazy title",

自:

title   = "{What} {a} {interesting} {title}",
title= "{What} {a} {boring} {title}",
title="{What} {a} {crazy} {title}",

所以:

title <any number of spaces> = <any number of spaces> " <words in title> ",

应替换为:

title <any number of spaces> = <any number of spaces> " <{Each} {word} {in} {title} {should} {be} {in} {bracket}> ",

我正在尝试通过 Python 中的正则表达式来做到这一点,但不知道出了什么问题。

我的代码:

re.sub(r'(title[s-]*=[s-]*")(b(w+)b)',r'1{2}',line)

仅在第一个单词中添加括号。

这在字符串的第一部分使用负前瞻:

>>> import re
... s = """title   = "It's an interesting title",
... title= "What a boring title",
... title="What a crazy title","""
... print(re.sub(r'(?!titles*=s*")b(S+)b',r'{1}',s))
title   = "{It's} {an} {interesting} {title}",
title= "{What} {a} {boring} {title}",
title="{What} {a} {crazy} {title}",

见 http://regex101.com/r/hL2lE6/6

更新:Avinash Raj 对标题中可能出现的特殊字符(如撇号)提出了一个很好的观点,所以我将w+更改为 S+ 并更新了示例文本以对其进行测试。

注意:如果您的标题包含以特殊字符结尾的单词,并且该字符需要包含在括号中,请参阅此处了解解决方案:http://regex101.com/r/hL2lE6/11

它使用 (?!titles*=s*")b([^"=s]+) .但是,您主要关心的是大写,因此可能无关紧要。在这种情况下,我建议保持简单并坚持使用 S+ .

这不可能通过re模块来实现。但是您可以通过如下所示的外部regex模块来实现这一点。

>>> import regex
>>> s = '''title   = "What a interesting title",
title= "What a boring title",
title="What a crazy title",'''
>>> print(regex.sub(r'(?m)((?:^titles*=s*"|G) *)([^"sn]+)', r'1{2}',s))
title   = "{What} {a} {interesting} {title}",
title= "{What} {a} {boring} {title}",
title="{What} {a} {crazy} {title}",

演示

G在上一个匹配的末尾或第一个匹配项的字符串开头断言位置。 G强制模式仅返回属于连续匹配链一部分的匹配项。

引用:

  • http://www.regular-expressions.info/continue.html
  • 正则表达式中"\G"锚点有什么用?

最新更新