I’m trying to split the following string "Name=='mynme' && CurrentTime<'2012-04-20 19:45:45'" into this:
Name
==
'myname'
&&
CurrentTime
<
'2012-04-20 19:45:45'
I have the following regex:
([+\\-*/%()]{1}|[=<>!]{1,2}|[&|]{2})
The problem is when using the above regex I get the following result:
Name
==
'myname'
&&
CurrentTime
<
'2012
-
04
-
20
19:45:45'
I practically need the regex to be quote aware.
Thanks
Update 1 regarding lordcheeto’s answer:
Your response is close. But the following is still not split correctly:
string input2 = "((1==2) && 2-1==1) || 3+1==4 && Name=='Stefan+123'";
What I need to do is to split a string into operators and operands. Something like this:
LeftOperand Operator RightOperand
Now, if any operator is between '' it should be ignored and the whole string between '' should be treated as an operand.
The string above should generate the following output:
(
(
1
==
2
)
&&
2
-
1
==
1
)
||
3
+
1
==
4
&&
Name
==
'Stefan+123'
Ok, assuming you want it to simply split on logical and relational operators, you can use this pattern:
This will also trim all whitespace from the returned strings.
Code:
Test:
http://goo.gl/XAm6J
Output:
Edit
Ok, with the additional constraints, you should be able to use this:
This will still trim all whitespace from the returned strings. It will, however, return empty strings if matches are right next to each other (e.g.
Name=='Stefan+123'). I was unable to work around that this time, but it’s not so important.If you import
System.LinqandSystem.Collections.Genericand make the results aList<string>, you can remove all empty strings from theListin one extra line like this (which is slower than using straight-up for loops):Code:
Test:
http://goo.gl/lkaoM
Output:
Additional Comments:
If you want to split on any other operators (e.g.,
<<,+=,=,-=,>>) as well (there’s a lot), or need anything else, just ask.