\"-ice cream- - hang out\"" />
开发者

Regex to replace hyphen in middle of a word

How can I replace a hyphens in the middle of a word using python3 and re.sub()?

"-ice-cream- - hang-out" -> "-ice cream- - hang out"

Thanks,

Barry

EDIT: I tried

self.lines = re.sub(r'\w(-)\w', " ", self.lines)
but wasn'开发者_JAVA技巧t sure how to proceed. I like the /b way of doing it.


re.sub(pattern, repl, string[, count, flags]) see docs.python.org

Your pattern would be r'\b-\b'

See the pattern here on Regexr

And replace this with a space (' ')

The r before the regex string deifnes a raw string, that means you don't need double escaping.

\b is a word boundary, that means it will match on a - when there is a word character before and after.


>>> re.sub(r'(\w)-(\w)', lambda m: '%s %s' % (m.groups()), '-ice-cream- hang-out')
'-ice cream- hang out'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜