0

I have this line:

newFile := strings.SplitN(scannn.Text(), "$", 2)[1]

So it returns the second field after $, but would like to use two delimiters whatever it matches on that line, for example 2 spaces or space and dollar: or $. A delimiter can be conformed of one or more characters.

2
  • 1
    Split using a regular expression. Commented Jul 25, 2020 at 22:45
  • @MuffinTop Could you provide the exact code replacement for that line? Commented Jul 25, 2020 at 23:17

2 Answers 2

3

If your delimiters form a pattern you can consider using the Split method of regexp package. For the case mentioned in the question, it would mean

newFile := regexp.MustCompile(" [ $]").Split(scannn.Text(), 2)

If your delimiters are plenty in number but uni-character(rune) you can use FieldsFunc.

Sign up to request clarification or add additional context in comments.

3 Comments

Very good. Although you are missing the [1] at the end, otherwise says cannot use newFile (type []string) as type string. Do you know what's its purpose?
The return type of the Split method is a slice of string. [1] is the index of the string in returned slice, i.e., the second string of the slice.
TLDR use newFile[1], but I would suggest doing a check on the length of the returned slice first.
0

My own answer:

To use multiple delimiters in Go.

1.Original question: use only $ as delimiter and get all the line text after it:

newFile := strings.SplitN(scannn.Text(), "$", 2)[1]

2.New question: use more than one delimiter, for example two spaces ( ) or space+dollar ( $):

2.1 Method one:

newFile := regexp.MustCompile(` | \*`).Split(scannn.Text(), 2)[1]

2.2 Method two:

newFile := regexp.MustCompile(" [ *]").Split(scannn.Text(), 2)[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.