2

Here If I am given a string aaaa|bbb, I want output as aaaa and bbb. If I use string.split("|") It returns each character of the string as separate Array of strings like

output[0]="a",output[1]="a",output[2]="a",output[3]="a",output[4]="a",output[5]="|",output[6]="b",output[&]="b",output[0]="b"

But I want it as output[0]=aaaa, output[1]=bbb;

Please help me

jmj
  • 237,923
  • 42
  • 401
  • 438
Abhinav Konda
  • 225
  • 1
  • 11

3 Answers3

1

You need to escape the | metacharacter:

string.split("\\|")
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

split() expects a regex, where | has a special meaning and you need to escape it.

string.split("\\|")
Raffaele Rossi
  • 1,079
  • 5
  • 11
1

Use proper escaping: string.split("\\|") or the helper function which has been created for exactly this purpose: string.split(Regexp.quote("|"))

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820