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
Related
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);
I tried to write a function in C# which removes the string between two strings. Like this:
string RemoveBetween(string sourceString, string startTag, string endTag)
At first I thought this is easy, but after some time I encountered more and more problems
So this is the easy case (All examples with startTag="Start" and endTag="End")
"Any Text Start remove this End between" => "Any Text StartEnd between"
But it should also be able to handle multiples without deleting the text between:
"Any Text Start remove this End between should be still there Start and remove this End multiple" => "Any Text StartEnd between should be still there StartEnd multiple"
It should always take the smallest string to remove:
"So Start followed by Start only remove this End other stuff" => "So Start followed by StartEnd other stuff"
It should also respect the order of the the Tags:
"the End before Start. Start before End is correct" => "the End before Start. StartEnd is correct"
I tried a RegEx which did not work (It could not handle multiples):
public string RemoveBetween(string sourceString, string startTag, string endTag)
{
Regex regex = new Regex(string.Format("{0}(.*){1}", Regex.Escape(startTag), Regex.Escape(endTag)));
return regex.Replace(sourceString, string.Empty);
}
And than I tried to work with IndexOf and Substring, but I do not see an end. And even if it would work, this cant be the most elegant way to solve this.
Here is a approach with string.Remove()
string input = "So Start followed by Start only remove this End other stuff";
int start = input.LastIndexOf("Start") + "Start".Length;
int end = input.IndexOf("End", start);
string result = input.Remove(start, end - start);
I use LastIndexOf() because there can be multiple starts and you want to have the last one.
You must sligthly modify your function to do a non-greedy match with ? and RegexOptions.RightToLeft to work with all your examples :
public static string RemoveBetween(string sourceString, string startTag, string endTag)
{
Regex regex = new Regex(string.Format("{0}(.*?){1}", Regex.Escape(startTag), Regex.Escape(endTag)), RegexOptions.RightToLeft);
return regex.Replace(sourceString, startTag+endTag);
}
You can use this:
public static string Remove(string original, string firstTag, string secondTag)
{
string pattern = firstTag + "(.*?)" + secondTag;
Regex regex = new Regex(pattern, RegexOptions.RightToLeft);
foreach(Match match in regex.Matches(original))
{
original = original.Replace(match.Groups[1].Value, string.Empty);
}
return original;
}
string data = "text start this is my text end text";
string startTag = "start";
string endTag = "end";
int startIndex = data.IndexOf(startTag)+ startTag.Length;
Console.WriteLine(data.Substring(startIndex, data.IndexOf(endTag)-startIndex));
Or you could try to use LINQ like showed here
public static string Remove(this string s, IEnumerable<char> chars)
{
return new string(s.Where(c => !chars.Contains(c)).ToArray());
}
I have this string here
string Thing1 = "12340-TTT";
string Thing2 = "®"
I am looking to use reg replace to replace the TTT with ®.
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", "®");
// 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 "®".
Try this:
string one = "1234-TTT";
string pattern = "TTT";
Regex reg = new Regex(pattern);
string two = "®";
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 );
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\""
how can I format below string
Address1=+1234+block+of+XYZ+Street+Address2=+Santa+Fe+Springs+State=+California
to string
Address1=+1234+block+of+XYZ+Street+&Address2=+Santa+Fe+Springs+&State=+California
The below regex doesnt work properly.could someone fix this?
string inputString = "Address1=+1234+block+of+XYZ+Street+Address2=+Santa+Fe+Springs+State=+California";
string outString = Regex.Replace(inputString,#"([\s])([a-zA-Z0-9]*)(=)","&$1");
I think you want this
Regex.Replace(inputString,#"\+([a-zA-Z0-9]+)=","+&$1=")
Or this if you want to allow any character other than + & = in keywords.
Regex.Replace(inputString,#"\+([^+&=]+)=","+&$1=")
If all you want to do is prefix "Address2" and "State" by an ampersand:
Regex.Replace(inputString, "(?=Address2=|State=)", "&");