String Replace Problem - c#

I have a string replace problem. I have a result like:
"Animal.Active = 1 And Animal.Gender = 2"
I want to replace something in this text.
Animal.Active part is returned from a database and sometimes it is returned with the Animal.Gender part.
When Animal.Gender part comes from the database I have to remove this And Animal.Gender part.
Also if the string has Animal.Active = 1, I have to remove Animal.Active = 1 And part. Note the And.
How can I do this?

You will need to use a regular expression (regex) to replace this, then, since you want to match a number.
string pattern = "And Animal\.Gender\s*=\s*[0-9]+";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Will work to replace "And Animal.Gender = #" with zero or more white spaces between the = sign.
You can do a similar replacement for the second request, with Animal.Active.

Granted this is a very specific solution that will undoubtedly become more complicated as you add more conditions, but here goes:
dbReturn =
dbReturn.Replace("And Animal.Gender","").Replace("Animal.Active = 1","");

Related

Exclude first and last quotation of string in regex result

I'm running a little c# program where I need to extract the escape-quoted words from a string.
Sample code from linqpad:
string s = "action = 0;\r\ndir = \"C:\\\\folder\\\\\";\r\nresult";
var pattern = "\".*?\"";
var result = Regex.Split(s, pattern);
result.Dump();
Input (actual input contains many more escaped even-number-of quotes):
"action = 0;\r\ndir = \"C:\\\\folder\\\\\";\r\nresult"
expected result
"C:\\folder\\"
actual result (2 items)
"action = 0;
dir = "
_____
";
result"
I get exactly the opposite of what I require. How can I make the regex ignore the starting (and ending) quote of the actual string? Why does it include them in the search? I've used the regex from similar SO questions but still don't get the intended result. I only want to filter by escape quotes.
Instead of using Regex.Split, try Regex.Match.
You don't need RegEx. Simply use String.Split(';') and the second array element will have the path you need. You can then Trim() it to get rid of the quotes and Remove() to get rid of the ndir part. Something like:
result = s.Split(';')[1].Trim("\r ".ToCharArray()).Remove(0, 7).Trim('"');

Matching Fields Wrapped in Punctuation but not Single Apostrophe

I have the following Regex that I use to translate fields in SQL strings
string posLookBehind = #"(?<=\p{P}*)\b";
string posLookAhead = #"\b(?=\p{P}*)";
string keyword = "FieldA";
string translatedKeyword = "FldA";
string strSql = "SELECT [FieldA] FROM SomeTableA;";
strSql = Regex.Replace(
strSql,
baseRegexLeft + keyword + baseRegexRight,
translatedKeyword,
RegexOptions.IgnoreCase);
For some keyword FieldA, the above regex would replace 'FieldA' with 'FldA' in each of the following: [FieldA], [FieldA + FieldB] et al. However, I now wish to restrict the regex. I do not want to match 'FieldA' note the single apostrophe.
So, I have changed the regex using regex subtraction to remove ' from the punctuation set:
string posLookBehind = #"(?<=[\p{P}-[']]*)\b";
string posLookAhead = #"\b(?=[\p{P}-[']]*)";
where the other code is the same. But this is still matching 'FieldA'. What am I doing wrong here?
Thanks for your time.
I think the reason behind this is the the star * in the look behind and the look ahead, because it matches zero or more, so after matching FieldA it self it then checks behind for zero or more punctuations that are not apostrophes but since there is an apostrophe it just matches zero times.
You can fix this by changing the star to a plus +:
string posLookBehind = #"(?<=[\p{P}-[']]+)\b";
string posLookAhead = #"\b(?=[\p{P}-[']]+)";
Or if there is only a single surrounding character all the time then:
string posLookBehind = #"(?<=[\p{P}-[']])\b";
string posLookAhead = #"\b(?=[\p{P}-[']])";

Regex pattern for text between 2 strings

I am trying to extract all of the text (shown as xxxx) in the follow pattern:
Session["xxxx"]
using c#
This may be Request.Querystring["xxxx"] so I am trying to build the expression dynamically. When I do so, I get all sorts of problems about unescaped charecters or no matches :(
an example might be:
string patternstart = "Session[";
string patternend = "]";
string regexexpr = #"\\" + patternstart + #"(.*?)\\" + patternend ;
string sText = "Text to be searched containing Session[\"xxxx\"] the result would be xxxx";
MatchCollection matches = Regex.Matches(sText, #regexexpr);
Can anyone help with this as I am stumped (as I always seem to be with RegEx :) )
With some little modifications to your code.
string patternstart = Regex.Escape("Session[");
string patternend = Regex.Escape("]");
string regexexpr = patternstart + #"(.*?)" + patternend;
The pattern you construct in your example looks something like this:
\\Session[(.*?)\\]
There are a couple of problems with this. First it assumes the string starts with a literal backslash, second, it wraps the entire (.*?) in a character class, that means it will match any single open parenthesis, period, asterisk, question mark, close parenthesis or backslash. You'd need to escape the the brackets in your pattern, if you want to match a literal [.
You could use a pattern like this:
Session\[(.*?)]
For example:
string regexexpr = #"Session\[(.*?)]";
string sText = "Text to be searched containing Session[\"xxxx\"] the result would be xxxx";
MatchCollection matches = Regex.Matches(sText, #regexexpr);
Console.WriteLine(matches[0].Groups[1].Value); // "xxxx"
The characters [ and ] have a special meaning with regular expressions - they define a group where one of the contained characters must match. To work around this, simply 'escape' them with a leading \ character:
string patternstart = "Session\[";
string patternend = "\]";
An example "final string" could then be:
Session\["(.*)"\]
However, you could easily write your RegEx to handle Session, Querystring, etc automatically if you require (without also matching every other array you throw at it), and avoid having to build up the string in the first place:
(Querystring|Session|Form)\["(.*)"\]
and then take the second match.

How would I use regular expressions to remove a parenthesised substring?

I have a regular expression (regex) question...
How would I use regular expressions to remove the contents in parenthesis in a string in C# like this:
"SOMETHING (#2)"
The part of the string I want to remove always appears within paranthesis and they are always # followed by some number. The rest of the string needs to be left alone.
Remove everything including the parenthesis
var input = "SOMETHING (#2) ELSE";
var pattern = #"\(#\d+\)";
var replacement = "";
var replacedString = System.Text.RegularExpressions.Regex.Replace(input, pattern, replacement);
Remove only contents within parenthesis
var input = "SOMETHING (#2) ELSE";
var pattern = #"(.+?)\(#\d+\)(.+?)";
var replacement = "$1()$2";
var replacedString = System.Text.RegularExpressions.Regex.Replace(input, pattern, replacement);

Find and Insert

I have a string that looks like (the * is literal):
clp*(seven digits)1*
I want to change it so that it looks like:
clp*(seven digits)(space)(space)1*
I'm working in C# and built my search pattern like this:
Regex regAddSpaces = new Regex(#"CLP\*.......1\*");
I'm not sure how to tell regex to keep the first 11 characters, add two spaces and then cap it with 1*
Any help is appreciated.
No need to use regex here. Simple string manipulation will do the job perfectly well.
var input = "clp*01234561*";
var output = input.Substring(0, 11) + " " + input.Substring(11, 2);
I agree with Noldorin. However, here's how you could do it with regular expressions if you really wanted:
var result = Regex.Replace("clp*12345671*", #"(clp\*\d{7})(1\*)", #"$1 $2");
If you just want to replace this anywhere in the text you can use the excluded prefix and suffix operators...
pattern = "(?<=clp*[0-9]{7})(?=1*)"
Handing this off to the regex replace with the replacement value of " " will insert the spaces.
Thus, the following one-liner does the trick:
string result = Regex.Replace(inputString, #"(?<=clp\*[0-9]{7})(?=1\*)", " ", RegexOptions.IgnoreCase);
Here is the regex, but if your solution is as simple as you stated above Noldorin's answer would be a clearer and more maintainable solution. But since you wanted regex... here you go:
// Not a fan of the 'out' usage but I am not sure if you care about the result success
public static bool AddSpacesToMyRegexMatch(string input, out string output)
{
Regex reg = new Regex(#"(^clp\*[0-9]{7})(1\*$)");
Match match = reg.Match(input);
output = match.Success ?
string.Format("{0} {1}", match.Groups[0], match.Groups[1]) :
input;
return match.Success;
}

Categories

Resources