Six*_*its 10 python regex hyphen
我正在寻找一个正则表达式匹配python中的带连字符的单词.
我能得到的最接近的是:'\ w + - \w + [ - w +]*'
text = "one-hundered-and-three- some text foo-bar some--text"
hyphenated = re.findall(r'\w+-\w+[-\w+]*',text)
Run Code Online (Sandbox Code Playgroud)
返回列表['one-hundered-and-three-','foo-bar'].
这几乎是完美的,除了'三'之后的尾随连字符.我只想要附加连字符,如果后面跟着'单词'.也就是说,而不是'[ - \w +]*',我需要像'( - \w +)*'这样的东西,我认为它会起作用,但不会(它返回['-three,'']).即匹配|后跟连字符后跟单词后跟hyphen_word零次或多次|的东西.
a'r*_*a'r 22
试试这个:
re.findall(r'\w+(?:-\w+)+',text)
Run Code Online (Sandbox Code Playgroud)
在这里,我们考虑一个带连字符的词: