Check multiple words in a string using Contains method - c#

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);

Related

How to replace words while keeping case?

I have a string as such:
string myString = "String testing string replace"
I want to take that string and give the word string a style. So the final string would be:
myString = "<span class='myclass'>String</span> testing <span class='myclass'>string</span> replace"
How can I do that programmatically? So that both instances of the word string keep their case?
Perhaps something like:
var myString2 = Regex.Replace(
myString,
Regex.Escape("string"),
"<span class='myclass'>$0</span>",
RegexOptions.IgnoreCase
);
The pattern is just the string you want to replace, escapes so if it had any characters in it that mean something to Regex (like a period) they match exactly. When a match occurs the whole match is stored in variable $0. This variable can be used in the replacement, so when we specify IgnoreCase it means that first match is on String, which means the replacement $0 is String.. the second match is on string
string myString = "String testing string replace";
string stringOut = "";
foreach (var word in myString.Split(new char[] { ' '}))
{
stringOut += $"<span class='myclass'>{word}</span> ";
}
Console.WriteLine(stringOut);

Remove numbers in specific part of string (within parentheses)

I have a string Test123(45) and I want to remove the numbers within the parenthesis. How would I go about doing that?
So far I have tried the following:
string str = "Test123(45)";
string result = Regex.Replace(str, "(\\d)", string.Empty);
This however leads to the result Test(), when it should be Test123().
tis replaces all parenthesis, filled with digits by parenthesis
string str = "Test123(45)";
string result = Regex.Replace(str, #"\(\d+\)", "()");
\d+(?=[^(]*\))
Try this.Use with verbatinum mode #.The lookahead will make sure number have ) without ( before it.Replace by empty string.
See demo.
https://regex101.com/r/uE3cC4/4
string str = "Test123(45)";
string result = Regex.Replace(str, #"\(\d+\)", "()");
you can also try this way:
string str = "Test123(45)";
string[] delimiters ={#"("};;
string[] split = str.Split(delimiters, StringSplitOptions.None);
var b=split[0]+"()";
Remove a number that is in fact inside parentheses BUT not the parentheses and keep anything else inside them that is not a number with C# Regex.Replace means matching all parenthetical substrings with \([^()]+\) and then removing all digits inside the MatchEvaluator.
Here is a C# sample program:
var str = "Test123(45) and More (5 numbers inside parentheses 123)";
var result = Regex.Replace(str, #"\([^()]+\)", m => Regex.Replace(m.Value, #"\d+", string.Empty));
// => Test123() and More ( numbers inside parentheses )
To remove digits that are enclosed in ( and ) symbols, the ASh's \(\d+\) solution will work well: \( matches a literal (, \d+ matches 1+ digits, \) matches a literal ).

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 can I replace string with regular expressions?

I replace my string as below;
string str = "Opps V 14";
str = str.Replace("V 14", "V14");
But numeric part of string is not static. Sometimes it can be "V 17", "V 13" etc..
How can I replace that with regular expressions globally?
This will replace the space between V and a digit with nothing:
string pattern = #"(?<=\bV) (?=\d)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, "");
(?<=\bV) is a lookbehind assertion and means "preceded by V", \b is a word boundary.
(?=\d) is a lookahead assertion and means "followed by a digit"
Lookaround assertions are not part of the match result but only checks. This is the reason why only the space is removed.
note: you must include using System.Text.RegularExpressions; at the begining of the file.
Assuming that except the number, rest of the string is static, then its as simple as removing the space after V:
str = str.Replace("V ","V");
class Program
{
static void Main(string[] args)
{
string str = "Opps V 14";
string[] temp = str.Split(' ');
str = String.Join(" ", temp.Take(2)) + temp.Last();
}
}

Replace any string between quotes

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\""

Categories