Question

In C#, i am trying to split the following string

(hello)(world)(hello)(world)

into an array of the following format

arr[0] = (
arr[1] = hello
arr[2] = )
arr[3] = (
arr[4] = world
arr[5] = )
arr[6] = (
arr[7] = hello
arr[8] = )
arr[9] = (
arr[10] = world
arr[11] = )

I am currently using the following regex expression to perform the split and it appears to be slow

Regex.Split(value1, @"(?<=\))|(?=\))|(?=\()|(?<=\()")

I am no expert with regex but I have a gut feeling that there could be another regex expression which provides the same functionality in an efficiently manner.

Wondering if there are better ways (more efficient regex expressions) to implement the same split in c#?

Was it helpful?

Solution

You could try to match these tokens instead:

Regex.Matches(value1, @"[()]|[^()]+")

Here the pattern [()]|[^()]+ matches either a single ( or ), or a sequence of characters except ( and ).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top