[英]Python/Java: How to Reverse a String Words but not special characters
I have an input string with Special characters: input= "the: sky is sunny" expected output = "sunny: is sky the"我有一个带有特殊字符的输入字符串: input="the:sky issunny" 预期输出 = "sunny: is sky the"
Need to reverse a string words but preserving special char in string.需要反转字符串单词但保留字符串中的特殊字符。
I have done simple string reverse, but that did not preserve the special characters :( Please help how to do this ? Thanks in advance.我已经完成了简单的字符串反转,但没有保留特殊字符:( 请帮助如何做到这一点?提前致谢。
Use re
:使用re
:
s1 = 'the: sky is sunny'
fmt = re.sub(r'\w+', '{}', s1)
s2 = fmt.format(*reversed(re.findall(r'\w+', s1)))
>>> s2
'sunny: is sky the'
Regex: \\w+
正则表达式: \\w+
\\w
: matches any word character (equivalent to [a-zA-Z0-9_]) \\w
:匹配任何单词字符(相当于 [a-zA-Z0-9_])
+
: matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy) +
:在一次和无限次之间匹配前一个令牌,尽可能多次,根据需要返回(贪婪)
Source: https://regex101.com/来源: https : //regex101.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.