Golang:删除除|以外的所有字符 来自字符串

SYZ*_*333 -2 regex string replace go

我需要删除除"|"之外的所有字符 和字符串中的空格.我不明白如何在Go中这样做.请帮忙.

字符串可能如下所示:

|| ||| |||| || ||||| ||| || |||| hello |
Run Code Online (Sandbox Code Playgroud)

我需要它来返回这个:

|| ||| |||| || ||||| ||| || ||||  |
Run Code Online (Sandbox Code Playgroud)

提前致谢!

pet*_*rSO 11

"我认为这是诱人的,如果你拥有的唯一工具是锤子,就像把它当作钉子一样对待所有东西." 亚伯拉罕马斯洛,科学心理学,1966年.

来自其他语言的程序员有时会将正则表达式视为锤子,并将所有文本视为钉子.

在Go中,保持简单高效,例如,

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func remove(s string) string {
    return strings.Map(
        func(r rune) rune {
            if r == '|' || unicode.IsSpace(r) {
                return r
            }
            return -1
        },
        s,
    )
}

func main() {
    s := "|| ||| |||| || ||||| ||| || |||| hello |"
    fmt.Println(s)
    s = remove(s)
    fmt.Println(s)
}
Run Code Online (Sandbox Code Playgroud)

输出:

|| ||| |||| || ||||| ||| || |||| hello |
|| ||| |||| || ||||| ||| || ||||  |
Run Code Online (Sandbox Code Playgroud)

一个简单的基准:

package main

import (
    "regexp"
    "testing"
)

var (
    s = "|| ||| |||| || ||||| ||| || |||| hello |"
    t string
)

func BenchmarkMap(b *testing.B) {
    for i := 0; i < b.N; i++ {
        t = remove(s)
    }
}

func BenchmarkRegexp(b *testing.B) {
    reg := regexp.MustCompile("[^| ]+")
    for i := 0; i < b.N; i++ {
        t = reg.ReplaceAllString(s, "")
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

BenchmarkMap         5000000           337 ns/op
BenchmarkRegexp      1000000          2068 ns/op
Run Code Online (Sandbox Code Playgroud)

包字符串

功能图

func Map(mapping func(rune) rune, s string) string
Run Code Online (Sandbox Code Playgroud)

Map返回字符串s的副本,其中所有字符都根据映射函数进行了修改.如果映射返回负值,则从字符串中删除该字符而不进行替换.


wil*_*.09 8

使用regex.ReplaceAllString:

ReplaceAllStringFunc返回src的副本,其中Regexp的所有匹配项都已替换为应用于匹配的子字符串的函数repl的返回值.repl返回的替换直接替换,不使用Expand.

例:

reg := regexp.MustCompile("[^| ]+")
origStr := "|| ||| |||| || ||||| ||| || |||| hello |"
replaceStr := reg.ReplaceAllString(origStr, "")
Run Code Online (Sandbox Code Playgroud)

文档:https: //golang.org/pkg/regexp/#Regexp.ReplaceAllString

GoPlay:https: //play.golang.org/p/rfZFuQMrNJ