-3

quick question. I have a random string, something like this:

"country=='CANADA'&&(role=='MANAGERL1'||role=='ADMIN'||role=='LOC_IND')&&Age>67"

I need to find and replace each substring that matches this pattern "role=='ROLENAME'" into

roles.indexOf('ROLENAME'), so in this example it I want to get a new string:

"country=='CANADA'&&(roles.indexOf('MANAGERL1')>=0||roles.indexOf('ADMIN')>=0||roles.indexOf('LOC_IND')>=0)&&Age>67"

How can I do this in C#, I mean using Regular Expressions (RegEx) ? What should be the regex expression? And if you know the shortest way to do the replacement, it would help a lot.

Thanks.

monstro
  • 6,254
  • 10
  • 65
  • 111
  • You haven't said what you want to use as a replacement. [Regex.Replace Method (String, String)](http://msdn.microsoft.com/en-us/library/xwewhkd1%28v=vs.110%29.aspx) could be a good place to start constructing your own code that we can help with. – Andrew Morton Jan 07 '15 at 20:21
  • Why would it matter what he wants to replace it with? He's asking for a regex that can match it. – The Muffin Man Jan 07 '15 at 20:22
  • I'd rather build a class that takes whatever query format this happens to be and tokenizes it internally and allows you to get back a string after you've modified any individual tokens. – The Muffin Man Jan 07 '15 at 20:24
  • Sorry, I added what I need to get ... – monstro Jan 07 '15 at 20:26
  • `roles.indexOf(...)` or `roles.indexOf(..)>=0` ? – L.B Jan 07 '15 at 20:29

1 Answers1

3

You need the static method System.Text.RegularExpressions.Regex.Replace.

Your pattern is @"role==('[^']*')".

Your replacement is @"roles.indexOf($1)".

Mark Shevchenko
  • 7,937
  • 1
  • 25
  • 29
  • Mark, since u are an expert in Regex, maybe u can suggest how to find and convert to lower case names of variables inside that string that matches a pattern (VarName is some name of variable): "VarName==" or "VarName!=" or "VarName<" or "VarName<=" or "VarName>=" or "VarName>", basically the left side of the comparison, "VarName" find and convert to "varname" ?? Regex is not my strong side :) – monstro Jan 09 '15 at 17:01
  • You need the [`Replace` method with `MatchEvaluator` parameter](http://msdn.microsoft.com/en-us/library/ht1sxswy(v=vs.100).aspx): `Regex.Replace(input, @"(\w+)([=<>!]+)('[^']*')", match => match.Groups[1].Value.ToUpper() + match.Groups[2].Value + match.Groups[3].Value);` I've used lambda function here. It's parameter `match` contains `Groups` property. Every group matches with every pair of parenthesis in the pattern, so `Groups[1].Value` contain a name of a variable, `[2]` contains operator, and `[3]` contains a constant. The lambda method must return a single string for entire pattern. – Mark Shevchenko Jan 09 '15 at 23:14