M
M
Muhammadkhon Abdullaev2020-08-26 19:35:15
go
Muhammadkhon Abdullaev, 2020-08-26 19:35:15

How to parse a string and change certain characters?

Hello! There is such a question:
How can a string be parsed and replace certain characters. For example:
Given: +999 99 999 99 99 or +999 (99) -999-99-99
Need to be: +999999999999.
I'm a beginner, so I can explain more easily.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WinPooh32, 2020-08-27
@Muhammadkhonofficial

Without regular expressions:
https://play.golang.org/p/SIqQunrMQHI

import (
  "strings"
)

func normalize(s string) string {
  var sb strings.Builder

  for _, r := range s {
    switch {
    case '0' <= r && r <= '9':
    case r == '+':
    default:
      continue
    }
    sb.WriteRune(r)
  }

  return sb.String()
}

With regulars:
https://play.golang.org/p/GYzsCTaEa9W
import (
  "regexp"
  "strings"
)
var re = regexp.MustCompile(`(?i)[\d\+]+`)

func normalize(s string) string {
  var sb strings.Builder
  subs := re.FindAllStringSubmatch(s, -1)
  
  for _, sub := range subs {
    sb.WriteString(sub[0])
  }
  
  return sb.String()
}

Or a variant with the replacement of characters:
var re = regexp.MustCompile(`(?m)[^+\d]`)
var str = `+999 (99)-999 9999`
fmt.Println(re.ReplaceAllString(str, ""))

The version without regular expressions is more economical in terms of processor and memory resources, but if the pattern changes, it will also require changing the function code.

D
Dmitry Shitskov, 2020-08-26
@Zarom

Replace spaces with "blank".
https://golang.org/pkg/strings/#ReplaceAll
strings.ReplaceAll("+999 99 999 99 99", " ", "")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question