Regex to remove string from string - c#

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

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

How to replace single quote in asp.net c#

I used Regex.Replace(jobdesc, #"[^\/\'-]+", " "); but its not working please help me I want to replace only (' and -) with blank space how to arrange this regex code.
You can use a simple replace like:
"your sentence".Replace("''"," ").Replace("-"," ");
Using Reg Exp you can do as below
string pattern = #"\-\'";
string input = "mynam-'is";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

Regex to replace multiple instances of "tokens" in the following format: [[TokenName:TokenValue]]?

I'm looking for a Regex that can replace any instance of [[Something:SomethingElse]] with an empty string.
Try this regex: \[\[.*?:.*?\]\]
string str = #"some string before pattern [[Something:SomethingElse]] between
pattern [[doesnt matter:at all]] after pattern";
string result = Regex.Replace(str, #"\[\[.*?:.*?\]\]", "");
Outout:
some string before pattern between pattern after pattern
Using Regex.Replace and LookArounds:
value = Regex.Replace(value, #"(?=\[\[)(.*?:.*?)(?<=\]\])", string.Empty);
Test case:
string value = "89as89d98as98d[[lksdlkfajks03:34]],[[939203902:ksadfjlkaklsdf]]9390290390ks";
Output:
value = "89as89d98as98d,9390290390ks"

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

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

Categories