I'm trying to replace a string,enclosed in curly brackets.
If I use the Replace method provided by the Regex class and I don't specify the curly brackets, the string is found and replaced correctly, but if I do specify the curly brackets like this: {{FullName}}, the text is left untouched.
var pattern = "{{" + keyValue.Key + "}}";
docText = new Regex(pattern, RegexOptions.IgnoreCase).Replace(docText, keyValue.Value);
Take this string as a example
Dear {{FullName}}
I want to replace it with John, so that the text ends up like this:
Dear John.
How can I express the regex, so that the string is found and replace correctly?
You don't need a regular expression if the key is just a string. Just replace "{{FullName}}" with "John". example:
string template = "Dear {{FullName}}";
string result = template.Replace("{{" + keyValue.Key + "}}", keyValue.Value);
Edit: addressing concerns that this doesn't work...
The following is a complete example. You can run it at https://dotnetfiddle.net/wnIkvf
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var keyValue = new KeyValuePair<string,string>("FullName", "John");
string docText = "Dear {{FullName}}";
string result = docText.Replace("{{" + keyValue.Key + "}}", keyValue.Value);
Console.WriteLine(result);
}
}
var keyValue = new KeyValuePair<string,string>("FullName", "John");
var pattern = "{{" + keyValue.Key + "}}";
Console.WriteLine(new Regex(Regex.Escape(pattern), RegexOptions.IgnoreCase).Replace("Dear {{FullName}}", keyValue.Value));
Output:
Dear John
Looking for "Dear {{FullName}}" to "Dear John"?
not a regex solution... but this is how I prefer to do it sometimes.
string s = "Dear {{FullName}}";
// use regex to replace FullName like you mentioned before, then...
s.Replace("{",string.empty);
s.Replace("}",string.empty);
If you actually want to use a regular expression, then escape your literal text to turn it into a regular expression pattern using Regex.Escape.
var keyValue = new KeyValuePair<string,string>("FullName", "John");
string docText = "Dear {{FullName}}";
var pattern = "{{" + keyValue.Key + "}}";
docText = new Regex(Regex.Escape(pattern), RegexOptions.IgnoreCase).Replace(docText, keyValue.Value);
docText will be Dear John
What I believe is that you really want to do is replace multiple things in a document.
To do so use the regex pattern I provide, but also use the regex replace match evaluator delegate. What that does, is that every match can be actively evaluated for each item and a proper item will be replaced as per C# logic.
Here is an example with two possible keywords setup.
string text = "Dear {{FullName}}, I {{UserName}} am writing to say what a great answer!";
string pattern = #"\{\{(?<Keyword>[^}]+)\}\}";
var replacements
= new Dictionary<string, string>() { { "FullName", "OmegaMan" }, { "UserName", "eddy" } };
Regex.Replace(text, pattern, mt =>
{
return replacements.ContainsKey(mt.Groups["Keyword"].Value)
? replacements[mt.Groups["Keyword"].Value]
: "???";
}
);
Result
Dear OmegaMan, I eddy am writing to say what a great answer!
The preceding example uses
Match Evaluator Delegate
Named match capture groups (?<{Name here}> …)
Set Negation [^ ] which says match until the negated item is found, in this case a closing curly }.
Related
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\""
I have a string, which represents part of xml.
string text ="word foo<tag foo='a' />another word "
and I need to replace particular words in this string. So I used this code:
Regex regex = new Regex("\\b" + co + "\\b", RegexOptions.IgnoreCase);
return regex.Replace(text, new MatchEvaluator(subZvyrazniStr));
static string subZvyrazniStr(Match m)
{
return "<FtxFraze>" + m.ToString() + "</FtxFraze>";
}
But the problem of my code is, that it also replaces string inside tags, which i don't want to. So what should I add, to replace words only outside tags?
Ex.: when I set variable co to "foo" I want to return "word <FtxFraze>foo</FtxFraze><tag foo='a' />another word"
Thanks
A simple trick like this may suffice in some cases if you are not that picky:
\bfoo\b(?![^<>]*>)
This is what you want
(?<!\<[\w\s]*?)\bfoo\b(?![\w\s]*?>)
works here
I had answered a related question here
Try this regex:
Regex r = new Regex(#"\b" + rep + #".*?(?=\<)\b", RegexOptions.IgnoreCase);
It is very basic question but i am not sure why it is not working. I have code where 'And' can be written in any of the ways 'And', 'and', etc. and i want to replace it with ','
I tried this:
and.Replace("and".ToUpper(),",");
but this is not working, any other way to do this or make it work?
You should check out the Regex class
http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
using System.Text.RegularExpressions;
Regex re = new Regex("\band\b", RegexOptions.IgnoreCase);
string and = "This is my input string with and string in between.";
re.Replace(and, ",");
words = words.Replace("AND", ",")
.Replace("and", ",");
Or use RegEx.
The Replace method returns a string where the replacement is visible. It does not modify the original string. You should try something along the lines of
and = and.Replace("and",",");
You can do this for all variations of "and" you may encounter, or as other answers have suggested, you could use a regex.
I guess you should take care if some words contain and, say "this is sand and sea". The word "sand" must not be influenced by the replacement.
string and = "this is sand and sea";
//here you should probably add those delimiters that may occur near your "and"
//this substitution is not universal and will omit smth like this " and, "
string[] delimiters = new string[] { " " };
//it result in: "this is sand , sea"
and = string.Join(" ",
and.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Length == 3 && s.ToUpper().Equals("AND")
? ","
: s));
I would also add smth like this:
and = and.Replace(" , ", ", ");
So, the output:
this is sand, sea
try this way to use the static Regex.Replace() method:
and = System.Text.RegularExpressions.Regex.Replace(and,"(?i)and",",");
The "(?i)" causes the following text search to be case-insensitive.
http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx
http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.100).aspx
Is there a regex pattern that can remove .zip.ytu from the string below?
werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222
Here is an answer using regex as the OP asked.
To use regex, put the replacment text in a match ( ) and then replace that match with nothing string.Empty:
string text = #"werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222";
string pattern = #"(\.zip\.ytu)";
Console.WriteLine( Regex.Replace(text, pattern, string.Empty ));
// Outputs
// werfds_tyer.abc_20111223170226_20111222.20111222
Just use String.Replace()
String.Replace(".zip.ytu", "");
You don't need regex for exact matches.
txt = txt.Replace(".zip.ytu", "");
Why don't you simply do above?
Don't really know what is the ".zip.ytu", but if you don't need exact matches, you might use something like that:
string txt = "werfds_tyer.abc.zip.ytu_20111223170226_20111222.20111222";
Regex mRegex = new Regex(#"^([^.]*\.[^.]*)\.[^.]*\.[^_]*(_.*)$");
Match mMatch = mRegex.Match(txt);
string new_txt = mRegex.Replace(txt, mMatch.Groups[1].ToString() + mMatch.Groups[2].ToString());
use string.Replace:
txt = txt.Replace(".zip.ytu", "");
Here is the method I use for more complex repaces. Check out the link: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(v=vs.110).aspx for a Regular Expression replace. I added the code below as well.
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
For example I have code below
string txt="I have strings like West, and West; and west, and Western."
I would like to replace the word west or West with some other word. But I would like not to replace West in Western.
Can I use regular expression in string.replace? I used
inputText.Replace("(\\sWest.\\s)",temp); It dos not work.
No, but you can use the Regex class.
Code to replace the whole word (rather than part of the word):
string s = "Go west Life is peaceful there";
s = Regex.Replace(s, #"\bwest\b", "something");
Answer to the question is NO - you cannot use regexp in string.Replace.
If you want to use a regular expression, you must use the Regex class, as everyone stated in their answers.
Have you looked at Regex.Replace? Also, be sure to catch the return value; Replace (via any string mechanism) returns a new string - it doesn't do an in-place replace.
Try using the System.Text.RegularExpressions.Regex class. It has a static Replace method. I'm not good with regular expressions, but something like
string outputText = Regex.Replace(inputText, "(\\sWest.\\s)", temp);
should work, if your regular expression is correct.
Insert the regular expression in the code before class
using System.Text.RegularExpressions;
below is the code for string replace using regex
string input = "Dot > Not Perls";
// Use Regex.Replace to replace the pattern in the input.
string output = Regex.Replace(input, "some string", ">");
source : http://www.dotnetperls.com/regex-replace
USe this code if you want it to be case insensitive
string pattern = #"\bwest\b";
string modifiedString = Regex.Replace(input, pattern, strReplacement, RegexOptions.IgnoreCase);
In Java, String#replace accepts strings in regex format but C# can do this as well using extensions:
public static string ReplaceX(this string text, string regex, string replacement) {
return Regex.Replace(text, regex, replacement);
}
And use it like:
var text = " space more spaces ";
text.Trim().ReplaceX(#"\s+", " "); // "space more spaces"
I agree with Robert Harvey's solution except for one small modification:
s = Regex.Replace(s, #"\bwest\b", "something", RegexOptions.IgnoreCase);
This will replace both "West" and "west" with your new word