【问题标题】:Regex to add quotes around hyphenated strings正则表达式在带连字符的字符串周围添加引号
【发布时间】:2020-08-29 18:33:11
【问题描述】:

我想在字符串中的所有带连字符的单词周围添加引号。

使用示例字符串,所需的函数add_quotes() 应该像这样执行:

>>> s = '{name = first-name}'
>>> add_quotes(s)
{name = "first-name"}

我知道如何使用 this Regex selector 查找所有出现的连字符作品,但不知道如何在原始字符串中的每个出现的地方添加引号。

>>> import re
>>> s = '{name = first-name}'
>>> re.findall(r'\w+(?:-\w+)+', s)
['first-name']

【问题讨论】:

    标签: python re


    【解决方案1】:

    正则表达式可用于标准库中的 Python 模块 re

    import re
    
    def add_quotes(s):
        return re.sub(r'\w+(?:-\w+)+', r'"\g<0>"', s)
    
    s = '{name = first-name}'
    add_quotes(s)  # returns '{name = "first-name"}'
    

    使用this selector 找到出现连字符的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-27
      • 2023-03-27
      • 2020-11-19
      • 2016-08-08
      • 2013-02-09
      • 2016-07-29
      • 2010-09-13
      • 2021-08-14
      相关资源
      最近更新 更多