【问题标题】:Regex to replace any character at a given position正则表达式替换给定位置的任何字符
【发布时间】:2020-03-19 11:21:01
【问题描述】:

我想将一个字符替换为另一个字符,该字符位于字符串中的特定位置。 示例:

This is a test string! Now comes a different one! And yet an another one to demonstrate what I want! Hello there! How can I achieve to replace all exclamation mark to point!

我知道我的角色在 21st 位置,因此我尝试了:.{21}(.)\K(.*?\1)+ 第一个捕获组有我想要的字符,我可以利用 \K 从最后一场比赛开始。但是,我怎样才能匹配字符串的其余部分?

期望的输出是: This is a test string. Now comes a different one. And yet an another one to demonstrate what I want. Hello there. How can I achieve to replace all exclamation mark to point. 提前致谢!

【问题讨论】:

    标签: regex pcre


    【解决方案1】:

    你可以使用

    ^.{21}\K.
    

    或者,如果有换行符,

    (?s)^.{21}\K.
    

    regex demo

    详情

    • (?s) - 一个 dotall 修饰符,使 . 也匹配换行符
    • ^ - 字符串开头
    • .{21} - 任意 21 个字符
    • \K - match reset operator
    • . - 任何一个字符。

    请注意,在许多情况下,您可能只使用组和反向引用,^(.{21}). -> $1<<YOUR_REPLACEMENT_STRING>>

    【讨论】:

    • 感谢 Wiktor,但我必须将每个感叹号替换为一个点(我已经编辑了我的原始帖子并添加了所需的输出)。
    • @Attila 您需要分两步完成,如果不支持后向模式中无限的模式长度,这是不可能的。
    猜你喜欢
    • 2020-04-18
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2015-11-30
    • 2014-10-27
    • 2016-06-06
    • 2013-05-11
    相关资源
    最近更新 更多