【问题标题】:How to use regex to replace string with fixed size of char如何使用正则表达式用固定大小的字符替换字符串
【发布时间】:2020-09-28 08:52:57
【问题描述】:

假设我有以下文字:

TimeOut_BN:1292 ms
TimeOut_BN:130 ms
TimeOut_BN:1313 ms
TimeOut_BN:1329 ms
TimeOut_BN:19 ms
TimeOut_BN:5 ms
TimeOut_BN:154 ms

我想用格式化数字(正好 4 个字符)替换所有数字

TimeOut_BN:1292 ms
TimeOut_BN: 130 ms
TimeOut_BN:1313 ms
TimeOut_BN:1329 ms
TimeOut_BN:  19 ms
TimeOut_BN:   5 ms
TimeOut_BN: 154 ms

我使用以下正则表达式来查找数字

BN:(.*)\sms

但我不知道如何判断“替换为正好 4 个字符”。

有没有办法做到这一点?


@revo 看起来不错,这个想法很好,但是当我在 regex101 上测试它时,我得到了:

TimeOut_BN:(?{1} 1292)(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} )(?{2}  130)(?{3}   ) ms
TimeOut_BN:(?{1} 1313)(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} 1329)(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} )(?{2}  )(?{3}   19) ms
TimeOut_BN:(?{1} )(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} )(?{2}  154)(?{3}   ) ms

【问题讨论】:

  • 你需要一个回调函数作为替换,或者一个条件替换支持(在 Boost、PCRE2 中可用)
  • 您使用哪种编程语言(如果有的话?)。
  • @Jan 我不会用编程语言,只会用记事本++
  • @Wiktor Stribiżew 如果您有一些示例或链接,将会找到。
  • 尝试找到^TimeOut_BN:\K(?:(\d{3})|(\d\d)|(\d))\b并替换为(?{1} $1)(?{2} $2)(?{3} $3)

标签: regex replace notepad++


【解决方案1】:

你或许可以一步到位,先尝试找到:

^TimeOut_BN:\K(?:(\d{3})|(\d\d)|(\d))\b

然后替换为

(?{1} $1)(?{2}  $2)(?{3}   $3)

【讨论】:

  • 因为你不能在那里测试它。它特定于 N++ 使用的 Boost 引擎。
  • 很好,我在notepad++上测试了它,它可以工作。你是怎么知道这些技巧的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 2021-10-07
  • 2021-11-29
相关资源
最近更新 更多