Python/Java:如何反转字符串单词而不是特殊字符

问题描述

我有一个带有特殊字符的输入字符串: input="the: 天空晴朗" 预期输出 = "sunny: is sky the"

需要反转字符串words但保留字符串中的特殊字符。

我做了简单的字符串反转,但没有保留特殊字符:( 请帮助如何做到这一点?提前致谢。

解决方法

使用from simqle import ConnectionManager cm = ConnectionManager("connections.yaml") sql = "SELECT name,age FROM people WHERE category = :category" params = {"category": 5} result = cm.recordset(con_name="my-database",sql=sql,params=params)

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'

\w+:匹配任意单词字符(相当于 [a-zA-Z0-9_])

\w:在一次和无限次之间匹配前一个令牌,尽可能多次,根据需要回馈(贪婪)

来源:https://regex101.com/