Replace any string between quotes - c#

Problem:
Cannot find a consistent way to replace a random string between quotes with a specific string I want. Any help would be greatly appreciated.
Example:
String str1 = "test=\"-1\"";
should become
String str2 = "test=\"31\"";
but also work for
String str3 = "test=\"foobar\"";
basically I want to turn this
String str4 = "test=\"antyhingCanGoHere\"";
into this
String str4 = "test=\"31\"";
Have tried:
Case insensitive Regex without using RegexOptions enumeration
How do you do case-insensitive string replacement using regular expressions?
Replace any character in between AnyText: and <usernameredacted#example.com> with an empty string using Regex?
Replace string in between occurrences
Replace a String between two Strings
Current code:
Regex RemoveName = new Regex("(?VARIABLE=\").*(?=\")", RegexOptions.IgnoreCase);
String convertSeccons = RemoveName.Replace(ruleFixed, "31");
Returns error:
System.ArgumentException was caught
Message=parsing "(?VARIABLE=").*(?=")" - Unrecognized grouping construct.
Source=System
StackTrace:
at System.Text.RegularExpressions.RegexParser.ScanGroupOpen()
at System.Text.RegularExpressions.RegexParser.ScanRegex()
at System.Text.RegularExpressions.RegexParser.Parse(String re, RegexOptions op)
at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options, Boolean useCache)
at System.Text.RegularExpressions.Regex..ctor(String pattern, RegexOptions options)
at application.application.insertGroupID(String rule) in C:\Users\winserv8\Documents\Visual Studio 2010\Projects\application\application\MainFormLauncher.cs:line 298
at application.application.xmlqueryDB(String xmlSaveLocation, TextWriter tw, String ruleName) in C:\Users\winserv8\Documents\Visual Studio 2010\Projects\application\application\MainFormLauncher.cs:line 250
InnerException:
found answer
string s = Regex.Replace(ruleFixed, "VARIABLE=\"(.*)\"", "VARIABLE=\"31\"");
ruleFixed = s;
I found this code sample at Replace any character in between AnyText: and with an empty string using Regex? which is one of the links i previously posted and just had skipped over this syntax because i thought it wouldnt handle what i needed.

var str1 = "test=\"foobar\"";
var str2 = str1.Substring(0, str1.IndexOf("\"") + 1) + "31\"";
If needed add check for IndexOf != -1

I don't know if I understood you correct, but if you want to replace all chars inside string, why aren't you using simple regular expresission
String str = "test=\"-\"1\"";
Regex regExpr = new Regex("\".*\"", RegexOptions.IgnoreCase);
String result = regExpr.Replace(str , "\"31\"");
Console.WriteLine(result);
prints:
test="31"
Note: You can take advantage of plain old XAttribute
String ruleFixed = "test=\"-\"1\"";
var splited = ruleFixed.Split('=');
var attribute = new XAttribute(splited[0], splited[1]);
attribute.Value = "31";
Console.WriteLine(attribute);//prints test="31"

var parts = given.Split('=');
return string.Format("{0}=\"{1}\"", parts[0], replacement);

In the case that your string has other things in it besides just the key/value pair of key="value", then you need to make the value-match part not match quote marks, or it will match all the way from the first value to the last quote mark in the string.
If that is true, then try this:
Regex.Replace(ruleFixed, "(?<=VARIABLE\s*=\s*\")[^\"]*(?=\")", "31");
This uses negative look-behind to match the VARIABLE=" part (with optional white space around it so VARIABLE = " would work as well, and negative look-ahead to match the ending ", without including the look-ahead/behind in the final match, enabling you to just replace the value you want.
If not, then your solution will work, but is not optimal because you have to repeat the value and the quote marks in the replace text.

Assuming that the string within the quotes does not contain quotes itself, you can use this general pattern in order to find a position between a prefix and a suffix:
(?<=prefix)find(?=suffix)
In your case
(?<=\w+=").*?(?=")
Here we are using the prefix \w+=" where \w+ denotes word characters (the variable) and =" are the equal sign and the quote.
We want to find anything .*? until we encounter the next quote.
The suffix is simply the quote ".
string result = Regex.Replace(input, "(?<=\\w+=\").*?(?=\")", replacement);

Try this:
[^"\r\n]*(?:""[\r\n]*)*

var pattern = "\"(.*)?\"";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
var replacement = regex.Replace("test=\"hereissomething\"", "\"31\"");

string s = Regex.Replace(ruleFixed, "VARIABLE=\"(.*)\"", "VARIABLE=\"31\"");
ruleFixed = s;
I found this code sample at Replace any character in between AnyText: and <usernameredacted#example.com> with an empty string using Regex? which is one of the links i previously posted and just had skipped over this syntax because i thought it wouldnt handle what i needed.

String str1 = "test=\"-1\"";
string[] parts = str1.Split(new[] {'"'}, 3);
string str2 = parts.Length == 3 ? string.Join(#"\", parts.First(), "31", parts.Last()) : str1;

String str1 = "test=\"-1\"";
string res = Regex.Replace(str1, "(^+\").+(\"+)", "$1" + "31" + "$2");

Im pretty bad at RegEx but you could make a simple ExtensionMethod using string functions to do this.
public static class StringExtensions
{
public static string ReplaceBetweenQuotes(this string str, string replacement)
{
if (str.Count(c => c.Equals('"')) == 2)
{
int start = str.IndexOf('"') + 1;
str = str.Replace(str.Substring(start, str.LastIndexOf('"') - start), replacement);
}
return str;
}
}
Usage:
String str3 = "test=\"foobar\"";
str3 = str3.ReplaceBetweenQuotes("31");
returns: "test=\"31\""

Related

Replace string but only for particular pattern in c#

I have 2 strings, one is main string and other is pattern string to be replaced. I want to replace the some part of main string with pattern string only if particular pattern is matched in main string.
Example:
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string pattern = "[lmn].[def].[ijk]";
i want final string as
[lmn].[def].[ijk] = [abc].[def].[ijk]
i.e. if only 2 part is there in string than only replace not for 3 parts
i am using:
mainstring = mainstring.Replace("[def].[ijk]",pattern);
but it replaces as,
[lmn].[def].[ijk] = [abc].[lmn].[def].[ijk]
^-------+-------^
|
+-- don't replace here
but I want as
[lmn].[def].[ijk] = [abc].[def].[ijk]
EDIT: Additional rule for the replacement:
You can touch left hand side or right hand side but the pattern should be alone without anything at before or after.
I am trying to follow this rule:
i.e. if only 2 part is there in string than only replace not for 3 parts
(interpreting it as replace only if the matching pattern is not inbetween other parts, or: neither preceded nor follwed by a .)
This regular expression should satisfy this rule above:
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
// will replace only right side
//string mainstring = "[abc].[def].[ijk] = [def].[ijk]";
string replacement = "[lmn].[def].[ijk]";
string pattern = #"(?<!\.)\[def\].\[ijk\](?!\.)";
string output = Regex.Replace(mainstring, pattern, replacement);
EDIT:
if you need to transform you basic pattern into a regex format replace both parentheses:
string searchPattern = "[def].[ijk]";
searchPattern = searchPattern.Replace("[", #"\[").Replace("]", #"\]");
and place the result in between the look ahead and look behind pattern:
string pattern = #"(?<!\.)" + searchPattern + #"(?!\.)";
Explanation:
(?<!\.): the pattern is called negative lookahead. It will match only if the preceding character is not a . (dot)
(?!\.): the pattern is called negative lookbehind. It will match only if the following character is not a . (dot)
the replacement of [ ] to \[ \] is necessary because regex treats the parentheses as an interval or group and matches every character between the parentheses. Like [0-9] will match any digit between 0 and 9. But if you use an escape sequence #"\[0-9\]" it will take the parentheses as a character and match the pattern "[0-9]". I hope it became a little clearer
does this work for you?
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string leftFillWith = "[lmn].[def].[ijk]";
string pattern = #"((\[lmn\]).)?((\[def\]).)?(\[ijk\])? =";
var expected= Regex.Replace(mainstring, pattern,match=> leftFillWith+" =" );
if only two parts are accepted:
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string leftFillWith = "[lmn].[def].[ijk]";
// string pattern = #"((\[lmn\]).)?((\[def\]).)?(\[ijk\])? ="; //if any number of parts is accepted on left
string pattern = #"(\[def\]\.\[ijk\])(\s)+="; //if only two parts are accepted
string expected = Regex.IsMatch(mainstring,pattern)? Regex.Replace(mainstring, pattern, match => leftFillWith + " ="):mainstring;
Not good but work;
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string pattern = "[lmn].[def].[ijk]";
string search ="[def].[ijk]";
string mainstring3 = "";
string[] mainstring2 = mainstring.Split(' ');
for (int i = 0; i < mainstring2.Length; i++)
{
if (mainstring2[i] == search)
{
mainstring2[i] = pattern;
}
if (i < mainstring2.Length - 1)
{
mainstring3 += mainstring2[i] + " ";
}
else
{
mainstring3 += mainstring2[i];
}
}
mainstring = mainstring3;
}

Check multiple words in a string using Contains method

I want to check multiple words in a string and want to replace them. Suppose that my string is
str= 20148(R)/(work)24553(r)
if(str.contains(("R)" || str.Contains("(work)"))
{
//Here I have to replace (R) and (Work) with space "".
// so that my string should be like this 20148/24553
}
How can check multiple words not by using loops, and in one flow.
I am new to c#. Please help me out
You don't need the if, just do:
var newStr = str.Replace("(R)"," ").Replace("(work)"," ");
If you want a space as you say or:
var newStr = str.Replace("(R)",string.Empty).Replace("(work)",string.Empty);
If you want an empty string.
Put R and r inside a character class to match both letters.
string str = "20148(R)/(work)24553(r)";
string result = Regex.Replace(str, #"\((?:[Rr]|work)\)", "");
Console.WriteLine(result);
IDEONE
OR
string str = "20148(R)/(work)24553(r)";
string result = Regex.Replace(str, #"(?i)\((?:R|work)\)", "");
Console.WriteLine(result);
IDEONE
Pattern Explanation:
(?i) (i modifier) would turn on the case-insensitive mode. So it would match both upper and lowercase letters.
\( Matches a literal ( symbol.
(?:) Non-capturing group.
R|work Matches a letter R or string work.(case-insensitive match)
\) Matches a literal ) symbol.
You could use the Regex.Replace method.
string str = "20148(R)/(work)24553(r)";
string str2 = Regex.Replace(str, "[(](?:R|work)[)]", "", RegexOptions.IgnoreCase);
Console.Writeline(str2); //prints 20148/24553
This says take the string str and match the pattern [(R|work)] and replace any instances with "" ignoring the case of the input string when doing the comparison (so it matches (R) and (r)).
With regex you can replace this
[(]\b(?:R|work)\b[)]
With empty string ""
Edit:
string str1 = "20148(R)/(work)24553(r)";
string str2 = Regex.Replace(str1, "[(]\b(?:R|work)\b[)]", "", RegexOptions.IgnoreCase);
Console.Writeline(str2);

Replacing all occurrences of alphanumeric characters in a string

I'm trying to replace all alphanumeric characters in my string with the character "-" using regex. So if the input is "Dune" i should get "----". currently though I'm getting just the single "-";
string s = "^[a-zA-Z0-9]*$";
Regex rgx = new Regex(s);
string s = "dune";
string result = rgx.Replace(s, "-");
Console.WriteLine(result);
Console.Read();
right now i know its looking for the string "dune" rather then the letters "d" "u" "n" "e". but i can find another class that would work.
Your regex is too greedy, remove the * and start end string matches. It should be
string s = "[a-zA-Z0-9]";
This will then only match 1 character anywhere in the string rather than all. You could also look at the shorthand for any alphanumeric
String s= "\w";
Try
string s = "[a-zA-Z0-9]";
Regex rgx = new Regex(s);
string s = "dune";
string result = rgx.Replace(s, "-");
Console.WriteLine(result);
Console.Read();
Why do you have one String s for your regular expression and another String s for your string? I would change this to eliminate confusion/error here.
Also to replace each alphanumeric character, you need to remove the beginning of string/end of string anchors ^ $ and the * quantifier meaning (0 or more times, matching the most amount possible)
Regex rgx = new Regex("[a-zA-Z0-9]");
string s = "dune";
string result = rgx.Replace(s, "-");
Console.WriteLine(result); //=> "----"

How to remove the exact occurence of characters from a string?

For Example, I have a string like :
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
I want to delete the charaters ,phani from str.
Now, I am using str = str.Replace(",phani", string.Empty);
then my output is : str="santhosh,ravi123,praveen,sathish,prakash";
But I want a output like : str="santhosh,ravi,phani123,praveen,sathish,prakash";
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
var words = str.Split(',');
str = String.Join(",", words.Where(word => word != "phani"));
the better choice is to use a Split and Join method.
Easy in Linq :
String str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
String token = "phani";
String result = String.Join(",", str.Split(',').Where(s => s != token));
(edit : I take time for testing and i'm not first ^^)
String.join(",", str.split(',').ToList().remove("phani"));
Removes any given name from the list.
How about
str = str.Replace(",phani,", ",");
This, however, does not work if "phani" is the last item in the string. To get around this, you could do this:
string source = "...";
source += ","; // Explicitly add a comma to the end
source = source.Replace(",phani,", ",").TrimEnd(',');
This adds a comma, replaces "phani" and removes the trailing comma.
A third solution would be this:
str = String.Join(",", str.Split(',').ToList().Remove("phani").ToArray());
Try to use with comma instead of;
string str = "santhosh,ravi,phani,phani123,praveen,sathish,prakash";
str = str.Replace(",phani,", ",");
Console.WriteLine(str);
Output will be;
santhosh,ravi,phani123,praveen,sathish,prakash
Here is a DEMO.
As Davin mentioned in comment, this won't work if phani is last item in the string. Silvermind's answer looks like the right answer.
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
string pattern = #"\b,phani,\b";
string replace = ",";
Console.WriteLine(Regex.Replace(str, pattern, replace));
Output:
santhosh,ravi,phani123,praveen,sathish,prakash
You may use the regular expression, but you have to take care of cases when your string starts or ends with the substring:
var pattern = #",?\bphani\b,?";
var regex = new Regex(pattern);
var result = regex.Replace(input, ",").Trim(',');
Shorter notation could look like this:
var result = Regex.Replace(input, #",?\bphani\b,?", ",").Trim(',');
Explanation of the regular expression: ,?\bphani\b,? matches the word phani, but only if preceded and followed by word-delimiter characters (because of the word boundary metacharacter \b), and it can be (but doesn't have to be) preceded and followed by the comma thanks to ,? which means none or more comma(s).
At the end we need to remove possible commas from the beginning and end of the string, that's why there's Trim(',') on the result.

How do I replace part of a string in C#?

Supposed I have the following string:
string str = "<tag>text</tag>";
And I would like to change 'tag' to 'newTag' so the result would be:
"<newTag>text</newTag>"
What is the best way to do it?
I tried to search for <[/]*tag> but then I don't know how to keep the optional [/] in my result...
Why use regex when you can do:
string newstr = str.Replace("tag", "newtag");
or
string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
Edited to #RaYell's comment
To make it optional, simply add a "?" AFTER THE "/", LIKE THIS:
<[/?]*tag>
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
Your most basic regex could read something like:
// find '<', find an optional '/', take all chars until the next '>' and call it
// tagname, then take '>'.
<(/?)(?<tagname>[^>]*)>
If you need to match every tag.
Or use positive lookahead like:
<(/?)(?=(tag|othertag))(?<tagname>[^>]*)>
if you only want tag and othertag tags.
Then iterate through all the matches:
string str = "<tag>hoi</tag><tag>second</tag><sometag>otherone</sometag>";
Regex matchTag = new Regex("<(/?)(?<tagname>[^>]*)>");
foreach (Match m in matchTag.Matches(str))
{
string tagname = m.Groups["tagname"].Value;
str = str.Replace(m.Value, m.Value.Replace(tagname, "new" + tagname));
}
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");

Categories