简体   繁体   English

Python正则表达式-替换基于字符串的重复模式

[英]Python Regular Expression - Replace String Based Repeated Patterns

I want to transform the string L^2 MT^-1 to L^2.MT^-1 . 我想将字符串L^2 MT^-1L^2.MT^-1 The dot replaces the space (\\s) only if it is between two word characters. 点仅在两个单词字符之间时才替换空格(\\ s)。 For example, if the string is 'lbf / s' no replacement will be applied. 例如,如果字符串为“ lbf / s”,则将不应用任何替换。

str1= 'L^2 M T^-1'

pattern = re.compile(r'(\w+\s\w+)+')
def pattern_match2(m):
    me = m.group(0).replace(' ', '.')
    return me

pattern.sub(pattern_match2, str1) # this produces L2.MT-1

How can i replace the string with dot (.) by repeated patterns? 如何通过重复模式用点(。)替换字符串?

You can use re.sub directly instead of finding a match and then using str.replace . 您可以直接使用re.sub而不是查找匹配项,然后使用str.replace Also, I'd use \\b instead of \\w since \\w matches any [a-zA-Z0-9_] , while \\b encapsulates it in a smarter way (in essence it is equivalent to (^\\w|\\w$|\\W\\w|\\w\\W) ) 另外,我将使用\\b代替\\w因为\\w匹配任何[a-zA-Z0-9_] ,而\\b以更智能的方式对其进行封装(本质上,它等效于(^\\w|\\w$|\\W\\w|\\w\\W)

import re

print(re.sub(r'\b(\s)\b', '.', 'L^2 M T^-1'))
# L^2.M.T^-1

print(re.sub(r'\b(\s)\b', '.', 'lbf / s'))
# lbf / s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM