AlexM
AlexM

Reputation: 1183

Regex to add quotes around hyphenated strings

I want to add quotes around all hyphenated words in a string.

With an example string, the desired function add_quotes() should perform like this:

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

I know how to find all occurances of hyphenated works using this Regex selector, but don't know how to add quotes around each of those occurances in the original string.

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

Upvotes: 0

Views: 40

Answers (1)

AlexM
AlexM

Reputation: 1183

Regex can be used to do this with Python Module re from the standard library.

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"}'

where the occurances of hyphenated words are found using this selector.

Upvotes: 1

Related Questions