问题描述

由于golang正则表达式不支持先行,我想知道有什么方法可以创建一个正则表达式来屏蔽任何具有10位数字的字符串.

Since golang regex does not support lookaheads, I was wondering is there any way i can create a regex that will mask any string having a 10 digit number.

func main() {
    s := "arandomsensitive information: 1234567890 this is not senstive: 1234567890000000"
    re := regexp.MustCompile(`\d{10}`)
    s = re.ReplaceAllString(s, "$1**********$2")
    fmt.Println(s)
}

是否可以获得这样的输出随机敏感信息:1234 ******,这并不敏感:1234567890000000"

Is it possible to get an output like this "arandomsensitive information: 1234****** this is not senstive: 1234567890000000"

还有可以尝试的无正则表达式的正则表达式吗?

Also any regex without lookaheads that i can try?

推荐答案

 ReplaceAllString 
ReplaceAllString
\b(\d{4})\d{6}\b
 $ 1 ****** 
 \ b(\ d {4})\ d {6} \ b 
\b(\d{4})\d{6}\b
package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "arandomsensitive information: 1234567890 this is not senstive: 1234567890000000"
    re := regexp.MustCompile(`\b(\d{4})\d{6}\b`)
    s = re.ReplaceAllString(s, "$1******")
    fmt.Println(s)
}

如果需要在任何非数字字符之间匹配10位数字,则可以使用

If you need to match the 10-digit number in between any non-digit characters, you may use

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "aspacestrippedstring1234567890buttrailingonehouldnotbematchedastitis20characters12345678901234567890"
    re := regexp.MustCompile(`((?:\D|^)\d{4})\d{6}(\D|$)`)
    fmt.Println(re.ReplaceAllString(s, "$1******$2"))
}
(?!\ d) 1234567890 1234567891 
(?!\d)1234567890 1234567891
result := re.ReplaceAllString(re.ReplaceAllString(s, "$1******$2"), "$1******$2")

正则表达式详细信息:

((?:\ D | ^)\ d {4}) \ d {6} (\ D | $)
((?:\D|^)\d{4})\d{6}(\D|$)

这篇关于正则表达式仅在golang中屏蔽任何匹配10位数字的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!