Skip to main content
 首页 » 编程设计

python之处理字符串中的转义字符

2024年10月17日27leader

我需要转换来自用户输入的字符串。用例非常简单:

  • 当字符串中有分号时,将字符串拆分为多行。
  • 当一行中有两个分号时,它们将被转换为一个。

理论上没有大问题。我使用 Python,但我相信使用其他语言的其他人会发现使用正则表达式也很容易。

import re 
 
def get_lines(text): 
    """Return a list of lines (list of str).""" 
    command_stacking = ";" 
    delimiter = re.escape(command_stacking) 
    re_del = re.compile("(?<!{s}){s}(?!{s})".format(s=delimiter), re.UNICODE) 
    chunks = re_del.split(text) 
 
    # Clean the double delimiters 
    for i, chunk in enumerate(chunks): 
        chunks[i] = chunk.replace(2 * command_stacking, command_stacking) 
 
    return chunks 

这似乎可行:

>>> get_lines("first line;second line;third line with;;a semicolon") 
['first line', 'second line', 'third line with;a semicolon'] 
>>> 

但是当有三个或四个分号时,它的行为并不像预期的那样。

多个分号被正则表达式忽略(它们应该被忽略),但是当用 ; 替换 ;; 时,;;;替换为;;,;;;;替换为;;...等。如果 2 被 1 取代、3 被 2 取代、4 被 3 取代,那就太好了……我可以向我的用户解释。

最好的解决方案是什么?

谢谢你的帮助,

请您参考如下方法:

re.sub 的 repl 参数可以是一个函数。

>>> s = 'a;;b;;;c;;;;d' 
>>> pattern = ';{2,}' 
>>> def f(m): 
    return m.group(0)[1:] 
 
>>> re.sub(pattern, f, s) 
'a;b;;c;;;d' 
>>>