Find and replace a specific number with regex - c#

I have the following string
string absoluteUri = "http://localhost/asdf1234?$asdf=1234&$skip=1234&skip=4321&$orderby=asdf"
In this string I would like to replace '$skip=1234' with '$skip=1244'
I have tried the following regular expression:
Regex.Replace(absoluteUri, #"$skip=\d+", "$skip=1244");
Unfortunately this is not working. What am I doing wrong?
The output should be:
"http://localhost/asdf1234?$asdf=1234&$skip=1244&skip=4321&$orderby=asdf"

$ is a special character in regular expressions (it's an anchor). You need to escape it in both the expression and in the replacement string, but they are escaped differently.
In the regular expression, you escape it with a \ but in the substitution you escape it by adding another $:
Regex.Replace(absoluteUri, #"\$skip=\d+", "$$skip=1244");

I can't add comment.
Just little fix. Need to do:
absoluteUri = Regex.Replace(absoluteUri, #"\$skip=\d+", "$skip=1244");

Related

Regex pattern with dot and quotation mark

How can I declare regex pattern in c#. Pattern starts with quotation mark and later is url address, some thing like below
\"www\.mypage\.pl //<- this is my pattern
string pattern = ? //todo: what should I put there
using verbatim strings:
string pattern = #"""www\.mypage\.pl";
You can use \ backslash to escape the regex semantic and revert to the actual literal. If you want to escape
"www.mypage.pl
you can use
\"[0-9a-zA-Z]*\.[0-9a-zA-Z]*\.[0-9a-zA-Z]*
^ this is not to escape the regex but the eventual string
if you use single quotes you don't need to escape the quotes!
Note that [0-9a-zA-Z]* will require some more characters like % and - and _ to capture all cases according to an RFC about URL syntax I can't produce now (it's easy to find online).
If you want to escape
\"www\.mypage\.pl
you have to escape the escapes as well:
\\\"[0-9a-zA-Z]*\\\.[0-9a-zA-Z]*\\\.[0-9a-zA-Z]*
Other answers have already handled (very nicely) how to put the phrase itself into a string.
To use it, you need to refer to the System.Text.RegularExpressions namespace, documentation for which is over at MSDN. As a (very) quick example:
System.Text.RegularExpressions.Regex.Replace(content,
regexPattern, newMatchContent);
will replace matches for the regular expression regexPattern in content with newMatchContent, and return the result.

Regex.Replace not working

I am having a strange issue with Regex.Replace
string test = "if the other party is in material breach of such contract and, after <span style=\"background-color:#ffff00;\">forty-five (45)</span> calendar days notice of such breach";
string final = Regex.Replace(test, "forty-five (45)", "forty-five (46)", RegexOptions.IgnoreCase);
the "final" string still shows "forty-five (45)". Any idea why? I am assuming it has to do something with the tag. How do I fix this?
Thanks
Escape the parenthesis. Depending on the language, might require two back slashes.
string final = Regex.Replace(test, "forty-five \(45\)", "forty-five (46)", RegexOptions.IgnoreCase);
Basically, parenthesis are defined to mean something, and by escaping the characters, you are telling regex to use the parenthesis character, and not the meaning.
Better yet, why are you using a Regex to do this at all? Try just doing a normal string replacement.
string final = test.Replace("forty-five (45)", "forty-six (46)")
Parentheses are special in regular expressions. They delimit a group, to allow for things such as alternation. For example, the regular expression foo(bar|bat)baz matches:
foo, followed by
either bar OR bat, followed by
baz
So, a regular expression like foo(bar) will never match the literal string foo(bar). What it will match is the literal string foobar. Consequently, you need to escape the metacharacters. In C#, this should do you:
string final = Regex.Replace(test, #"forty-five \(45\)", "forty-five (46)", RegexOptions.IgnoreCase);
The #-quoted string helps avoid headaches from excessive backslashes. Without it, you'd have to write "forty-five \(45\)".
If you are unable to escape the parenthesis, put them in a character class:
forty-five [(]45[)]

C# Using Regular Expressions

The following works in vb.net, and basically only allows characters on a standard US Keyboard. Any other character pasted gets deleted. I use the following regular expression code:
"[^A-Za-z0-9\[\{\}\]`~!##$%\^&*\(\)_\-+=\\/:;'""<>,\.|? ]", "")
However when I try to use it in C# it won't work, I used '\' as a escape sequence. C# seems a bit different when it comes to escape sequences? Any help would be appreciated.
Prefix the string with #. That's it. From there you can use the regex string from VB as is (including doubling up on the " character).
// Note: exact same string you're using, only with a # verbatim prefix.
string regex = #"[^A-Za-z0-9\[\{\}\]`~!##$%\^&*\(\)_\-+=\\/:;'""<>,\.|? ]";
string crazy = "hĀečlĤlŁoźtƢhǣeǮrȡe";
Console.WriteLine(Regex.Replace(crazy, regex, ""));
Output:
hellothere
Prefix your string with "#" and prefix quotes within the string with "\".
I.e. this string
abc\def"hij
in C# would be encoded as
#"abc\def\"hij"
You need to escape your " character. Do this by putting a \ before your " character.
"[^A-Za-z0-9[{}]`~!##$%\^&*()_-+=\/:;'""<>,.|? ]"
should become
"[^A-Za-z0-9[{}]`~!##$%\^&*()_-+=\/:;'\"\"<>,.|? ]"
If you use the #prefix before this, it will treat the backslash literally instead of an escape character and you wont get the desired result.
Escape your characters:
"[^A-Za-z0-9[{}]`~!##$%\^&*()_-+=\\/:;'\"<>,.|? ]"
A good tool for regular expression design and testing (free) is:
http://www.radsoftware.com.au/regexdesigner/
You need to escape you regex for use in C#
[^A-Za-z0-9\[\{\}\]`~!##$%\^&*\(\)_\-+=\\/:;'\"<>,\.|? ]
Try this one!

How do I replace an actual asterisk character (*) in a Regex expression?

I have a statement:
I have a string such as
content = "* test *"
I want to search and replace it with so when I am done the string contains this:
content = "(*) test (*)"
My code is:
content = Regex.Replace(content, "*", "(*)");
But this causes an error in C# because it thinks that the * is part of the Regular Expressions Syntax.
How can I modify this code so it changes all asterisks in my string to (*) instead without causing a runtime error?
Since * is a regex metacharacter, when you need it as a literal asterisk outside of a character class definition, it needs to be escaped with \ to \*.
In C#, you can write this as "\\*" or #"\*".
C# should also have a general purpose "quoting" method so that you can quote an arbitrary string and match it as a literal.
See also
Regular expressions and escaping special characters
Full list of what needs to be escaped, where/when
You can escape it:
\*
You don't need a regular expression in this simple scenario. You can use String.Replace:
content = content.Replace("*", "(*)");
Use Regex.Escape() It will take all of the string and make it into something you can use as part of a regex.
Use \\* instead of * in regex.replace call

Replace '$' using Regex

I want to replace
! = change
# = static(does not)
$ = Want to replace
I got a string like this #!$!
How do I replace the $ with something else?
EDIT: I need to use Regex as the string may appear anywhere!
You don't need a regular expression, just use the String.Replace method:
String result = input.Replace("$", "somethingElse");
As a side note: The way that you would do this with a regular expression would be like this:
String result = Regex.Replace(input, #"\$", "somethingElse");
Notice that I have escaped the $ with a backslash since $ usually means match the end of the string.
Take a look at System.Text.RegularExpressions.Regex.Replace method.
Regex.Replace("#!$!", "!(.*)!", "replacement value");
Why do you want some RegExp for string replacement. You can just use string.Replace() fundtion.
also, check out Rubular, a great RegEx Tester.
Using the String class' .Replace() method would do the trick but, if you really want to use RegEx, this is a great RegEx site that I use quite often.
Regular Expression Library
You should be able to find what you're looking for there.

Categories