regex for formatting words - c#

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=)", "&");

Related

Edit Hyperlink in a PDF Using iTextSharp [duplicate]

Supposed I have the following string:
string str = "<tag>text</tag>";
And I would like to change 'tag' to 'newTag' so the result would be:
"<newTag>text</newTag>"
What is the best way to do it?
I tried to search for <[/]*tag> but then I don't know how to keep the optional [/] in my result...
Why use regex when you can do:
string newstr = str.Replace("tag", "newtag");
or
string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
Edited to #RaYell's comment
To make it optional, simply add a "?" AFTER THE "/", LIKE THIS:
<[/?]*tag>
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
Your most basic regex could read something like:
// find '<', find an optional '/', take all chars until the next '>' and call it
// tagname, then take '>'.
<(/?)(?<tagname>[^>]*)>
If you need to match every tag.
Or use positive lookahead like:
<(/?)(?=(tag|othertag))(?<tagname>[^>]*)>
if you only want tag and othertag tags.
Then iterate through all the matches:
string str = "<tag>hoi</tag><tag>second</tag><sometag>otherone</sometag>";
Regex matchTag = new Regex("<(/?)(?<tagname>[^>]*)>");
foreach (Match m in matchTag.Matches(str))
{
string tagname = m.Groups["tagname"].Value;
str = str.Replace(m.Value, m.Value.Replace(tagname, "new" + tagname));
}
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");

Regex to remove string from string

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

How do I replace part of a string in C#?

Supposed I have the following string:
string str = "<tag>text</tag>";
And I would like to change 'tag' to 'newTag' so the result would be:
"<newTag>text</newTag>"
What is the best way to do it?
I tried to search for <[/]*tag> but then I don't know how to keep the optional [/] in my result...
Why use regex when you can do:
string newstr = str.Replace("tag", "newtag");
or
string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");
Edited to #RaYell's comment
To make it optional, simply add a "?" AFTER THE "/", LIKE THIS:
<[/?]*tag>
string str = "<tag>text</tag>";
string newValue = new XElement("newTag", XElement.Parse(str).Value).ToString();
Your most basic regex could read something like:
// find '<', find an optional '/', take all chars until the next '>' and call it
// tagname, then take '>'.
<(/?)(?<tagname>[^>]*)>
If you need to match every tag.
Or use positive lookahead like:
<(/?)(?=(tag|othertag))(?<tagname>[^>]*)>
if you only want tag and othertag tags.
Then iterate through all the matches:
string str = "<tag>hoi</tag><tag>second</tag><sometag>otherone</sometag>";
Regex matchTag = new Regex("<(/?)(?<tagname>[^>]*)>");
foreach (Match m in matchTag.Matches(str))
{
string tagname = m.Groups["tagname"].Value;
str = str.Replace(m.Value, m.Value.Replace(tagname, "new" + tagname));
}
var input = "<tag>text</tag>";
var result = Regex.Replace(input, "(</?).*?(>)", "$1newtag$2");

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

How to Format a string to be a part of URL?

I need to remove all chars that cant be part of urls, like spaces ,<,> and etc.
I am getting the data from database.
For Example if the the retrieved data is: Product #number 123!
the new string should be: Product-number-123
Should I use regex? is there a regex pattern for that?
Thanks
Here is a an example on how to generate an url-friendly string from a "normal" string:
public static string GenerateSlug(string phrase)
{
string str = phrase.ToLower();
str = Regex.Replace(str, #"[^a-z0-9\s-]", ""); // invalid chars
str = Regex.Replace(str, #"\s+", " ").Trim(); // convert multiple spaces into one space
str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); // cut and trim it
str = Regex.Replace(str, #"\s", "-"); // hyphens
return str;
}
You may want to remove the trim-part if you are sure that you always want the full string.
Source
An easy regex to do this is:
string cleaned = Regex.Replace(url, #"[^a-zA-Z0-9]+","-");
To just perform the replacement of special characters like "<" you can use Server.UrlEncode(string s). And you can do the opposite with Server.UrlDecode(string s).

Categories