Smeterlink
Smeterlink

Reputation: 786

Use multiple delimiters in golang with strings.SplitN

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.

Upvotes: 0

Views: 1948

Answers (2)

Smeterlink
Smeterlink

Reputation: 786

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]

Upvotes: 0

Vaibhav Mishra
Vaibhav Mishra

Reputation: 445

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.

Upvotes: 3

Related Questions