I need to replace:
string input = "%someAlphabets%.ZIP"
string replaceWith = "Hello"
string result = "Hello.ZIP"
I tried with Regex.Replace(inputString,"[%][A-Za-z][%]", replacedWith); but it is not working.
The problem in your expression is that, there is only one alphabet in between % signs. You need to repeat the alphabets.
Regex.Replace(inputString,"[%][A-Za-z]{1,}[%]", replacedWith);
Try this:
string input= "%someAlphabets%.ZIP"
string regex = "(%.*%)";
string result = Regex.Replace(input, regex, "Hello");
It doesn't care if the name is alphabet only but that you can change by changing the .* caluse to your selection logic.
As already mentioned in the comments, you don't need RegEx for this.
More simpler alternatives may be:
Using string.Format
string.Format("{0}", input)`
Using string interpolation
var input = "Hello";
var result = $"{input}.zip";
Using string.Replace method
var input = "%pattern%.ZIP"
var with = "Hello"
var result = input.Replace("%pattern%", with);
Related
I have strings that sometimes start like this:
"[1][v5r,vi][uk]
Other times like this:
[1][v5r,vi][uk]
How can I remove the " when it appears at the start of a string using Regex? I know I need to do something like this, but not sure how to set it up:
regex = new Regex(#"(\n )?\[ant=[^\]]*\]");
regex.Replace(item.JmdictMeaning, ""));
If the string always starts with [1]:
int indexOfFirstElement = item.IndexOf("[1]");
if (indexOfFirstElement > 0)
item = item.Substring(indexOfFirstElement);
If you just want to start at the first [:
int indexOfFirstElement = item.IndexOf('[');
if (indexOfFirstElement > 0)
item = item.Substring(indexOfFirstElement);
Simpler than Regex, which is probably overkill for this problem.
Here you go
string input =#" ""[1][v5r,vi][uk]";
string pattern = #"^\s*""?|""?\s*$";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, "");
Console.WriteLine(result);
You can find my Example here in dotnetfiddle
string.StartsWith will do the trick
string str = "\"[1][v5r,vi][uk]";
if(str.StartsWith('"'))
str = str.Substring(1);
It can be done using indexOf and Substring
string str = "\"a[1][v5r,vi][uk]";
Console.WriteLine(str.Substring(str.IndexOf('[')));
use TrimStart() to remove this character if exists
string str = "\"a[1][v5r,vi][uk]";
str= str.TrimStart('\"');
I have a string "http://www.something.com/test/?pt=12"
I want to replace pt=12 by pt=13 using regex.
The string after replace will be : "http://www.something.com/test/?pt=13"
How can I achieve this in C#?
string result = "";
Regex reg = new Regex("(.*)(pt=12)");
Match regexMatch = reg.Match("http://www.something.com/test/?pt=12");
if(regexMatch.Success){
result = regexMatch.Groups[1].Value + "pt=13"
}
I suppose you know the pt= part. I also presume that the param value is a number.
Then, you can use the following regex replacement:
var newval = 13;
var res = Regex.Replace(str, #"\?pt=[0-9]+", string.Format("?pt={0}", newval));
If the param can be non-first in the query string, replace \? with [?&].
Note that you could use the System.UriBuilder class. It has a Query property that you can use to rebuild the query string.
I want to match only numbers in the following string
String : "40’000"
Match : "40000"
basically tring to ignore apostrophe.
I am using C#, in case it matters.
Cant use any C# methods, need to only use Regex.
Replace like this it replace all char excpet numbers
string input = "40’000";
string result = Regex.Replace(input, #"[^\d]", "");
Since you said; I just want to pick up numbers only, how about without regex?
var s = "40’000";
var result = new string(s.Where(char.IsDigit).ToArray());
Console.WriteLine(result); // 40000
I suggest use regex to find the special characters not the digits, and then replace by ''.
So a simple (?=\S)\D should be enough, the (?=\S) is to ignore the whitespace at the end of number.
DEMO
Replace like this it replace all char excpet numbers and points
string input = "40’000";
string result = Regex.Replace(input, #"[^\d^.]", "");
Don't complicate your life, use Regex.Replace
string s = "40'000";
string replaced = Regex.Replace(s, #"\D", "");
I have a string in this format "string1;string2;string3;...;stringn"
; as a delimiter
I need to delete some string value of which I know, say valueForDelete
I use string.Split(';') method to find my value, delete it and then create a new string without deleted value.
I'm wondering is it possible to make this process easy with regex?
var values = "string1;string2;string3;string4";
var cleanedValues = String.Join(";",
values.Split(';')
.Where(x => x != "string3")
.ToArray())
Regex is a useful tool, and could be used for this, but often hard to maintain. Something like the above would likely provide an easier to maintain solution. Regex can be tricky if your string also contain regex characters. As a bonus, this is easy to extend.
static string CleanItUp(string values, params string[] removeMe)
{
return String.Join(";",
values.Split(';')
.Except(removeMe)
.ToArray());
}
Used like.
var retString = CleanItUp("string1;string2;string3;", "string1", "string2");
// returns "string3"
Why not just:
string s = "string1;string2;string3;valueForDelete;string4"
s = s.Replace("valueForDelete;", string.Empty).Replace("valueForDelete", string.Empty);
The second replace is for if the value is the last one.
However possible with RegEx, using Split and Join will be your easiest, most functional choice. If you had a more complex method of choosing what Strings to delete, you could use the Where clause.
String input = "string1;string2;string3";
String valueForDelete = "string2";
String[] parts = input.Split(';');
var allowed = parts.Where(str => !str.Equals(valueForDelete));
String output = String.Join(";", allowed);
If you are simply removing an exact value than String.Replace would be better.
Use this Regex to find valueForDelete: (?<=;|^)valueForDelete(?=;|$)
const string Pattern = #"(?<=;|^)string3(?=;|$)";
var s = "string1;string2;string3;string4;string5;";
var res = Regex.Replace(s, Pattern, string.Empty);
Regex will do that but not sure that for what you are asking it would be faster. .Split is fast. If you were spitting on something more complex then you would have to use regex. I assume you are using StringBuilder to build the new string? String += is slow. When you new the StringBuilder make it the size you expect.
For Replacement ensuring no other data is affected (using LINQ):
string test = "string1;string2;string3;valueForDelete;stringn";
test = String.Join(";", test.Split(';').Where(s => s != "valueForDelete"));
For simple replacement (using String.Replace()):
string test = "string1;string2;string3;valueForDelete;stringn";
test = test.Replace("valueForDelete;", "");
Couldn't you just say
var myString = "string1;string2;string3;string4;string5;";
myString = myString.Replace("string3;", "");
The result would be a myString with the value "string1;string2;string4;string5;"
EDIT: Created as a regex
public static Regex regex = new Regex("(?:^|;)string3(;|$)",
RegexOptions.CultureInvariant | RegexOptions.Compiled
);
myString = regex.Replace(myString, ";");
...only flaw I see at the moment is if myString = "string3"; it results in myString = ";";
Why Can't you just do this?
public static string Replace(string input)
{
input = input.Replace("valueToDelete;", "");
return input ;
}
i have a string:
string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"
i need to extract 15939
it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it
String result = Path.GetFileName("\\\\Tecan1\\tecan #1 output\\15939-E.ESY").Split('-')[0];
Perhaps?
This regex does the trick for the input string you provided:
var input = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY";
var pattern = #".*\\(\d{5})-";
var result = Regex.Match(input, pattern).Groups[1].Value;
But I actually like Brad's solution using Path.GetFileName more :-)
Try (based on your answer in the comments about the \ character):
string result = myString.SubString(myString.LastIndexOf(#"\") + 1, 5);