dsm0688 2018-02-15 15:57
浏览 359

替换字符串中除最后4个字符外的所有字符

Using Go, how do I replace all characters in a string with "X" except the last 4 characters?

This works fine for php/javascript but not for golang as "?=" is not supported.

\w(?=\w{4,}$)

Tried this, but does not work. I couldn't find anything similar for golang

(\w)(?:\w{4,}$)

JavaScript working link

Go non-working link

  • 写回答

3条回答 默认 最新

  • duanjianfu1398 2018-02-15 16:14
    关注

    Create a Regexp with

    re := regexp.MustCompile("\w{4}$")
    

    Let's say inputString is the string you want to remove the last four characters from. Use this code to return a copy of inputString without the last 4 characters:

    re.ReplaceAllString(inputString, "")
    

    Note: if it's possible that your input string could start out with less than four characters, and you still want those characters removed since they are at the end of the string, you should instead use:

    re := regexp.MustCompile("\w{0,4}$")
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源