Regex to remove duplicate letters but not numbers

前端 未结 1 638
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 23:12

What is the appropriate regex to remove adjacent duplicate letters but not numbers?

For example:

p11ppppl  --> p11pl

I had the f

相关标签:
1条回答
  • 2021-01-19 23:38

    I would do it like this (visualized here):

    /([a-zA-Z])(?=\1)/g
    

    Here's an example in Python:

    In [21]: re.sub(r'([a-zA-Z])(?=\1)', '', 'p11ppppl')
    Out[21]: 'p11pl'
    

    You could also use:

    /([\D])(?=\1)/g
    

    for everything except digits, or:

    /([\w])(?=\1)/g
    

    for all "word characters".

    As @Casimir et Hippolyte mentioned in the comments, we can also use:

    /([a-zA-Z])\1+/g
    

    with \1 as the replacement string, which may be a better approach.

    0 讨论(0)
提交回复
热议问题