C# Regular Expression

I have a string which is like
field1 - field2 '<=>' 20. Any one of  <=, <, = , >=, >,<> can be present in the '<=>'. I have to split the string to give me the LHS, RHS and the symbol, which can be one of the 6 mentioned above. Is it possible to do this using Regular Expressions or should I write custom code?
Ex: field1 - field2 <= 20 to my parser should give me field1 -field2, <= and 20 as output.
supreeths84Asked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
Move the <> to the beginning:

string value = "field1 - field2 <= 20";
Match m = Regex.Match(value, "(.*?)(<>|<=?|>=?|=)(.*)");

if (m.Success)
{
    string LHS = m.Groups[1].Value;
    string OP = m.Groups[2].Value;
    string RHS = m.Groups[3].Value;
}

Open in new window


[edit]

I screwed up ">=". Corrected above.

[/edit]
0
 
Terry WoodsIT GuruCommented:
I'd try matching with pattern:

(.*?)([<=>]{1,2})(.*?)

and looking at the 3 resulting groups.
0
 
käµfm³d 👽Commented:
Try:

string value = "field1 - field2 <= 20";
Match m = Regex.Match(value, "(.*?)(<=?|=?>|=|<>)(.*)");

if (m.Success)
{
    string LHS = m.Groups[1].Value;
    string OP = m.Groups[2].Value;
    string RHS = m.Groups[3].Value;
}

Open in new window

0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
supreeths84Author Commented:
@TerryAtOpus: Can you please help me with some example code?
0
 
Terry WoodsIT GuruCommented:
Note that I'm assuming that values like these won't be present:
><
==
<<
>>
=<
=>
as the pattern will consider those valid.
0
 
supreeths84Author Commented:
No, the symbol would be <,=,>,<>,<=,>=
0
 
supreeths84Author Commented:
@kaufmed: The regular expression doesnt work for <>
0
 
Terry WoodsIT GuruCommented:
Perhaps try (building on kaufmed's code):

Match m = Regex.Match(value, "(.*?)(\\<=?|=?>|=|<>)(.*?)");
0
 
supreeths84Author Commented:
Thanks Kaufmed. It works.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.