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.
Related
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);
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('\"');
Lets say i have string like this Test%Test and i have stored strings like this:
Test123Test
TestTTTTest
Test153jhdsTest
123Test
TEST123
So what i want is when i type in textbox Test it would filter me everything with Test in itselft and that will get me all strings which is easy, but i want to type in Test%Test and it needs to filter me everything that has Test[anything]Test in itself (so result would be first, second and third string). How can i do it?
a simple solution using a regex is:
string[] values = new string[] { "Test123Test",
"TestTTTTest",
"Test153jhdsTest",
"123Test",
"TEST123" };
string searchQuery = "Test%Test";
string regex = Regex.Escape(searchQuery).Replace("%", ".*?");
string[] filteredValues = values.Where(str => Regex.IsMatch(str, regex)).ToArray();
Or for a single match:
string value = "Test123Test";
string searchQuery = "Test%Test";
string regex = Regex.Escape(searchQuery).Replace("%", ".*?");
if ( Regex.IsMatch(value, regex) )
{
// do something with the match...
}
We replace % with a regular expression (. = any character, * = zero or more times, ? = lazy quantifier). You can learn more about regular expressions here
I'm writing a c# code that divide a string into two different groups. a string is pipe-delimited as example below:
there could be an empty space between two pipes.
number of pipes to "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w" are fixed; In this case, there are 4 pipes.
string value = "122312121|test value||test value 2|5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w|123456789|123456789";
const string sPattern = #"What should it be here?????";
var regex = new Regex(sPattern);
var match = regex.Match(value);
if (match.Success)
{
var begin = match.Groups["begin"].Value;
var middle = match.Groups["middle"].Value;
var end = match.Groups["end"].Value;
}
I am trying to get the output of the code to return as following:
begin = "122312121|test value||test value 2|"
middle = "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w"
end = "|123456789|123456789"
However, I'm so new to regular expression, and I have tried to write a regular expression for variable sPattern, but could not produce the right regular expression for it. Could any please help? Thanks.
you should use String.Split
string [] sarray = value.Split('|')
What that will do is give you the array
{"122312121", "test value", "" , "test value" , "2", "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w", "123456789", "123456789"}
and 5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w will be in sarray[5]
If you're looking for a regular expression to match this and want to use a regular expression rather than .Split, you could try this:
"^((.*?[|]){4})(.*?)([|].*)*$"
or more explicitly:
"^(?<begin>(.*?[|]){4})(?<middle>.*?)(?<end>[|].*)*$"
This is based on the fact that you said the number of pipes before your long string is fixed (at four).
Your code would then read as follows:
string value = "122312121|test value||test value 2|5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w|123456789|123456789";
const string sPattern = #"^((.*?[|]){4})(.*?)([|].*)*$";
var regex = new Regex(sPattern);
var match = regex.Match(value);
if (match.Success)
{
var begin = match.Groups[1].Value;
var middle = match.Groups[3].Value;
var end = match.Groups[4].Value;
}
The trick may be to escape the pipe character:
const string sPattern = #"(?<begin>[^|]*\|[^|]*\|[^|]*\|[^|]*\|)" +
"(?<middle>[^|]*)" +
"(?<end>\|.*)";
You could use String.Split and some Linq to do what you need
Rough example:
string value = "122312121|test value||test value 2|5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w|123456789|123456789";
string[] split = value.Split('|');
string begin = string.Join("|", split.Take(4));
string middle = split.Skip(4).Take(1).FirstOrDefault();
string end = "|" + string.Join("|", split.Skip(5).Take(2));
Returns
begin = "122312121|test value||test value 2|"
middle = "5GOdNF7Q5fK5O9QKiZefJEfO1YECcX1w"
end = "|123456789|123456789"
Here's another one:
^(?<begin>(.*?\|){4})(?<middle>.*?(?=\|))(?<end>.*)
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 ;
}