0

I'd like to do a regex split on multiple words, not just characters

For example the string:

and(animal = fish)or(food = meat)

Should give me:

1: (animal = fish)
2: (food = meat)
Lars
  • 9,976
  • 4
  • 34
  • 40

1 Answers1

1
Regex.Split("and(animal = fish)or(food = meat)", @"and|or")

Gives you:

[0]: ""
[1]: "(animal = fish)"
[2]: "(food = meat)"

If you want to retain the delimiters use:

Regex.Split("and(animal = fish)or(food = meat)", @"(and)|(or)")

Gives you:

[0]: ""
[1]: "and"
[2]: "(animal = fish)"
[3]: "or"
[4]: "(food = meat)"
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
Lars
  • 9,976
  • 4
  • 34
  • 40
  • 3
    This doesn't work correctly if one of the desired strings contains one of the split word, for example `"and(animal = horse)or(food = meat)"` – Bill Tür stands with Ukraine Mar 12 '20 at 15:34
  • 1
    @Lars did you just answer your own question immediately after asking it? – Chris Sandvik Mar 12 '20 at 15:36
  • 2
    @ChrisSandvik, https://stackoverflow.com/help/self-answer, But here I see no gain. – Drag and Drop Mar 12 '20 at 15:41
  • @DragandDrop interesting, I did not know that this was encouraged – Chris Sandvik Mar 12 '20 at 15:43
  • @ChrisSandvik, Many great Self Answer out there : like [1](https://stackoverflow.com/questions/2003505/how-do-i-delete-a-git-branch-locally-and-remotely), [2](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python), [3](https://stackoverflow.com/questions/247621/what-are-the-correct-version-numbers-for-c). note that the first one has 38k upvotes. – Drag and Drop Mar 12 '20 at 16:16
  • Generally, when I'm trying to find an answer on stackoverflow and I can't find it, but I eventually figure it out on my own, I try to add a "self-answer" so it's there for the next person – Lars Mar 12 '20 at 21:35