Can I use regular expressions with String.Replace in C#? - c#

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

Related

C# Regex replace with Regex

I have a problem, I want to replace every "[[:de:<text>]]" with "{{de|<text>}}" in some text. I tried with
output = Regex.Replace(input, "[[:de:(.*)]]", "{{de|(.*)}}");
but it doesnt copy the <text>.
I have no other idea how to replace this correctly.
Hope you can help me.
Use a lazy dot pattern and backreferences and escape the [ symbols:
output = Regex.Replace(input, #"\[\[:de:(.*?)]]", "{{de|$1}}");
If the text between de: and ]] can contain line breaks, use RegexOptions.Singleline modifier.
See the regex demo.
If you encapsulate everything inside groups, you can benefit of a MatchEvaluator. Try it online.
public static void Main()
{
var input = "[[:de:Hello World]]";
var pattern = #"(\[\[:de:)(.+)(\]\])";
var output = Regex.Replace(input, pattern, m => "{{de|" + m.Groups[2].Value + "}}");
Console.WriteLine(output);
}
output
{{de|Hello World}}
Do you really need regex ? I think you can only use string replace method;
output = input.Replace("[[:de:(.*)]]", "{{de|(.*)}}");

Regex to replace a string between special characters in c#

I have a situation where I have a string in which I have to replace a part that lies between special characters.
I can do the same using substrings and length,but that is the dirty way.
Is there any better way of doing this using regex?
e.g. of the string is
string str1 = "This is the <![CDATA[ SampleDataThatNeedsToBeReplaced ]]";
string repl = "Replacement Text";
I need a regex to get the output as
This is the Replacement Text
I did try a few regex like the following
result = Regex.Replace(str1, #"(?<=CDATA\[)(\w+?)(?=\]\])", repl);
I also tried
Regex x = new Regex("(\\[CDATA\\])(.*?)(\\[\\]\\]\\])");
string Result = str1.Replace(text, "$1" + repl + "$3");
did not get any results.
Any help is appreciated.
Regex.Replace (
"This is the <![CDATA[ SampleDataThatNeedsToBeReplaced ]]",
#"<!\[CDATA\[(.+)]]",
"Replacement Text");
Note that in case you need it ; the old text (between the inner brackets) is available as group1 (and so can be referenced via $1)

problem in regular expression

I am having a regular expression
Regex r = new Regex(#"(\s*)([A|B|C|E|G|H|J|K|L|M|N|P|R|S|T|V|Y|X]\d(?!.*[DFIOQU])(?:[A-Z](\s?)\d[A-Z]\d))(\s*)",RegexOptions.IgnoreCase);
and having a string
string test="LJHLJHL HJGJKDGKJ JGJK C1C 1C1 LKJLKJ";
I have to fetch C1C 1C1.This running fine.
But if a modify test string as
string test="LJHLJHL HJGJKDGKJ JGJK C1C 1C1 ON";
then it is unable to find the pattern i.e C1C 1C1.
any idea why this expression is failing?
You have a negative look ahead:
(?!.*[DFIOQU])
That matches the "O" in "ON" and since it is a negative look ahead, the whole pattern fails. And, as an aside, I think you want to replace this:
[A|B|C|E|G|H|J|K|L|M|N|P|R|S|T|V|Y|X]
With this:
[A-CEGHJ-NPR-TVYX]
A pipe (|) is a literal character inside a character class, not an alternation, and you can use ranges to help hilight the characters that you're leaving out.
A single regex might not be the best way to parse that string. Or perhaps you just need a looser regex.
You are searching for a not a following DFIOQU with your negative look ahead (?!.*[DFIOQU])
In your second string there is a O at the end in ON, so it must be failing to match.
If you remove the .* in your negative look ahead it will only check the directly following character and not the complete string to the end (Is it this what you want?).
\s*([ABCEGHJKLMNPRSTVYX]\d(?![DFIOQU])(?:[A-Z]\s?\d[A-Z]\d))\s*
then it works, see it here on Regexr. It is now checking if there is not one of the characters in the class directly after the digit, I don't know if this is intended.
Btw. I removed the | from your first character class, its not needed and also some brackets around your whitespaces, also not needed.
As I understood you need to find the C1C 1C1 text in your string
I've used this regex for do this
string strRegex = #"^.*(?<c1c>C1C)\s*(?<c1c2>1C1).*$";
after that you can extract text from named groups
string strRegex = #"^.*(?<c1c>C1C)\s*(?<c1c2>1C1).*$";
RegexOptions myRegexOptions = RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = #"LJHLJHL HJGJKDGKJ JGJK C1C 1C1 LKJLKJ";
string secondStr = "LJHLJHL HJGJKDGKJ JGJK C1C 1C1 ON";
Match match = myRegex.Match(strTargetString);
string c1c = match.Groups["c1c"].Value;
string c1c2 = match.Groups["c1c2"].Value;
Console.WriteLine(c1c + " " +c1c2);

C# regual expression needed

I have a bunch of text and in that text I would like to replace every "EXAMPLE" word that does NOT contain a a-z or A-Z character in front of it.. so something like "[^a-z]EXAMPLE"..
But when deleting I just want to delete the "EXAMPLE", not the misc character in front of it or any characters behind it...
So in "BLABLAEXAMPLBLA EXAMPLEBLA" i want to output "BLABLAEXAMPLBLA BLA"
I hope this is preety clear :)
Thank you for your time!
You can achieve this using negative lookbehind:
string cleanString = Regex.Replace(originalString, "(?<![a-zA-Z])EXAMPLE", "");
You can also use match evaluator. I think more elastic but more complicated too...
var regex = new Regex("[^a-z](?<a>EXAMPLE)");
var text = "BLABLAEXAMPLBLA EXAMPLEBLA";
MatchEvaluator evaluator = RemoveExample;
text = regex.Replace(text, evaluator);
...
private static string RemoveExample(Match m)
{
return m.Value.Replace(m.Groups["a"].Value, "");
}

C# regular expression to find custom markers and take content

I have a string:
productDescription
In it are some custom tags such as:
[MM][/MM]
For example the string might read:
This product is [MM]1000[/MM] long
Using a regular expression how can I find those MM tags, take the content of them and replace everything with another string? So for example the output should be:
This product is 10 cm long
I think you'll need to pass a delegate to the regex for that.
Regex theRegex = new Regex(#"\[MM\](\d+)\[/MM\]");
text = theRegex.Replace(text, delegate(Match thisMatch)
{
int mmLength = Convert.ToInt32(thisMatch.Groups[1].Value);
int cmLength = mmLength / 10;
return cmLength.ToString() + "cm";
});
Using RegexDesigner.NET:
using System.Text.RegularExpressions;
// Regex Replace code for C#
void ReplaceRegex()
{
// Regex search and replace
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"\[MM\](?<value>.*)\[\/MM\]", options);
string input = #"[MM]1000[/MM]";
string replacement = #"10 cm";
string result = regex.Replace(input, replacement);
// TODO: Do something with result
System.Windows.Forms.MessageBox.Show(result, "Replace");
}
Or if you want the orginal text back in the replacement:
Regex regex = new Regex(#"\[MM\](?<theText>.*)\[\/MM\]", options);
string replacement = #"${theText} cm";
A regex like this
\[(\w+)\](\d+)\[\/\w+\]
will find and collect the units (like MM) and the values (like 1000). That would at least allow you to use the pairs of parts intelligently to do the conversion. You could then put the replacement string together, and do a straightforward string replacement, because you know the exact string you're replacing.
I don't think you can do a simple RegEx.Replace, because you don't know the replacement string at the point you do the search.
Regex rex = new Regex(#"\[MM\]([0-9]+)\[\/MM\]");
string s = "This product is [MM]1000[/MM] long";
MatchCollection mc = rex.Matches(s);
Will match only integers.
mc[n].Groups[1].Value;
will then give the numeric part of nth match.

Categories