C# ASP.NET Reg Replace...Replace string with another string - c#

I have this string here
string Thing1 = "12340-TTT";
string Thing2 = "®"
I am looking to use reg replace to replace the TTT with &reg.
I am told using reg replace it does not matter if its uppercase or lowercase.
How would I go about doing this?

string input = "12340-TTT";
string output = Regex.Replace(input, "TTT", "&reg");
// Write the output.
Console.WriteLine(input);
Console.WriteLine(output);
Console.ReadLine();
This should do the trick. You find "TTT" in a string and replace it with "&reg".

Try this:
string one = "1234-TTT";
string pattern = "TTT";
Regex reg = new Regex(pattern);
string two = "&reg";
string result = reg.Replace(one, two);
Console.WriteLine(result);
should give you the desired Result. And just for a good read if you should ever need some more complicated Regular Expressions: http://msdn.microsoft.com/en-us/library/vstudio/xwewhkd1.aspx

correct me if i'm wrong but i think it is same with that of replacing a string on a variable like this:
string Thing1 = "12340-TTT";
string Thing2 = Regex.Replace(Thing1 , "®", "anyString");
got it from here:
http://www.dotnetperls.com/regex-replace
cheers:)

For this, you can use the Regex.Replace method (documentation here)
There are several overloaded versions, but the most direct one for this is the Regex.Replace(String input, String regexPattern, String replacementString) version:
string Thing1 = "12340-TTT";
string Thing2 = "®";
string newString = System.Text.RegularExpressions.Regex.Replace(Thing1, "[Tt]{3}", Thing2);
If you are unfamiliar with regular expressions, the [Tt] define specific character group (any characters matching one of ones specified) and the {3} just indicates that it must be appear 3 times. So, this will do a case-insensitive search for a string of 3 T's (e.g., TTT, ttt, TtT, tTt, etc.)
For more on basic regex syntax, you can look here: http://www.regular-expressions.info/reference.html

Also, between the RegexOptions you can pass to the regex there is the IgnoreCase to make it case insensitive:
string Thing1 = "12340-TTT";
string Thing2 = "®"
var regex = new Regex("TTT", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( Thing1 , Thing2 );

Related

How can I replace "XX,XXX" with "XX XXX"?

I need to replace string like "XX,XXX" with "XX XXX". The string "XX,XXX" is in another string, e.g:
"-1299-5,"XXX,XXXX",trft,4,0,10800"
The string is fetched from a text file. I want to split the string by ",". But the comma in the substring led to the wrong result.
The X represents a char. I think regex can help, who can give me the right regex expression.
This expression,
(.*"[^,]*),([^,]*".*)
with a replacement of $1 $2 might work.
Demo
Example
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = #"(.*""[^,]*),([^,]*"".*)";
string substitution = #"\1 \2";
string input = #"-1299-5,""XXX,XXXX"",trft,4,0,10800";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
}
}
Simply, use 'Replace' to replace char from your string.
var test = "XXX,XXXX";
var filtered = test.Replace(',', ' ');
Console.WriteLine(filtered);
Output :
XXX XXXX

Combine two regular expressions in C#

I have a problem with writting a reg exp for a string like this in C#
String correct = "<a>link</a>";
String wrong = "link</a>";
I know how to select the first in a reg exp example
string regExp = "^(<a>)";
Ans i know how to select the last one
string regExp = "(</a>)$";
But how could i combine this two, to one
Please use:
Regex regex = new Regex("<a>(.*)</a>");
string correct = "<a>link</a>";
bool okBool = regex.IsMatch(correct); // true
string wrong = "link</a>";
bool wrongBool = regex.IsMatch(wrong); //false
Or as mentioned by Ilya Ivanov, you can use this regex:
Regex regex = new Regex("^<a>(.*)</a>$");

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

Regex to match pattern in C#

I have a string in the following format
ABC=23:Qasd=56:Def=40.44
I would like to replace all the strings (ABC=, Qasd= and Def=) with empty string. The string after = can be anything. So my output string would be
23:56:40.44
It would be great if you can let me know the regex for that in C#
(^|:)[^=]*=
replaced with
$1
Matches the beginning of a string or a : and everything until and including =.
It is replaced with $1 to keep :.
C#
string strTargetString = #"ABC=23:Qasd=56:Def=40.44";
var myRegex = new Regex(#"(^|:)[^=]*=");
var result = myRegex.Replace(strTargetString, #"$1");
//result: 23:56:40.44
More examples:
ABC=hello:Qasd=56:Def=40.44 => hello:56:40.44
Match
^[^=]+=|(?<=:)[^=]+=
and replace with string.Empty
Regex.Replace("ABC=23:Qasd=56:Def=40.44", #"^[^=]+=|(?<=:)[^=]+=", string.Empty);

Replace strings in file

I have to replace in a following manner
if the string is "string _countryCode" i have to replace it as "string _sCountryCode"
as you can see where there is _ I replace it with _s followd be next character in capitals ie _sC
more examples:
string _postalCode to be replaced as string _sPostalCode
string _firstName to be replace as string _sFirstName
Please help.
Preferably answer in C# syntax
Not sure I understand why, but perhaps something like:
static readonly Regex hungarian =
new Regex(#"(string\s+_)([a-z])", RegexOptions.Compiled);
...
string text = ...
string newText = hungarian.Replace(text, match =>
match.Groups[1].Value + "s" +
match.Groups[2].Value.ToUpper());
Note that the regex won't necessarily spot examples such as (valid C#):
string
_name = "abc";
If the pattern of the strings are as you have shown, then you do not need to go for a regex. You can do this using Replace method of the string class.
StringBuilder ss=new StringBuilder();
string concat="news_india";//or textbox1.text;
int indexs=concat.LastIndexOf("_")+1;//find "_" index
string find_lower=concat.Substring(indexs,1);
find_lower=find_lower.ToUpper(); //convert upper case
ss.Append(concat);
ss.Insert(indexs,"s"); //s->what ever u like give "+your text+"
ss.Insert(indexs+1,find_lower);
try this..its will work

Categories