C# Using Regular Expressions - c#

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!

Related

regexp for c#, matching teams inside backspace

I'm having trouble with my c# code.
I have stored a string object when I print it out it prints out "username" and when I view it in the debugger it is shown as "\"username\"". How can I replace "\ with whitespace in the variable? It is stopping me from making comparison operations.
I tried with
memberNameStripped = teamMemberName.Replace(#"\", "");
But it does not replace the "\ so how can I do it?
Thanks in advance.
Why regex? Use String.Trim to remove leading and trailing quotes("):
memberNameStripped = memberNameStripped.Trim('"');
It's efficient and clear.
The \ is an escape character, what you probably want to replace is the double quote "
So try:
memberNameStripped = teamMemberName.Replace("\"", "");
In debugger it is shown as "\"username\"" because it is a quoted string. This is why it prints out "username". You could get rid of quotes using Replace("\"", "")

Find and replace a specific number with regex

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

Regex, MVS does not like my Regex strings, how do I make it comply

So in microsoft visual studio I have a string that is compiled into a regex. My string is "#(\d+(.\d+)?)=(\d+(.\d+)?)". I cannot compile my program because I get an error saying that \d is a unrecognized escape character. How do I tell it to shut up and let me regex like a pro?
Begin your string with #, that causes the compiler to leave (almost) all characters alone, unescaped (the exception is ", which can be escaped as ""):
#"#(\d+(.\d+)?)=(\d+(.\d+)?"
The problem is that c# does not like the \d inside the string. Use a verbatim string instead
string pattern = #"#(\d+(.\d+)?)=(\d+(.\d+)?)";
The "#" denotes it. C# will not look for escape sequences in the string. If you have to escape a " use two "".
Of cause you can use normal strings. but then you will have to escape the backslashes
string pattern = "#(\\d+(.\\d+)?)=(\\d+(.\\d+)?)";
If you're using a normal string, you need to escape your backslashes, like so:
"#(\\d+(.\\d+)?)=(\\d+(.\\d+)?)"
Basically, you're putting a literal string into C#; the C# compiler sees the string first, and tries to interpret \d as an escape sequence (which doesn't exist, hence error). Therefore, you use \\d to get the C# compiler to see the string as \d, which then gets passed to the regex engine (which does recognize \d as something meaningful). (yes, if you want to match a literal backslash in your regex pattern, you need to use \\\\)
But in C#, you have the alternative of just prepending the string with # to get the compiler to leave the string alone (though " still needs escaping), so that would be like this:
#"#(\d+(.\d+)?)=(\d+(.\d+)?)"
You could also use a verbatim string literal (I prefer to use these because of readability).
Use #"(#\d+(.\d+)?)=(\d+(.\d+)?)"
The #" sign indicates that the string shouldn't interpret escaped characters (A character prefixed by a \) until the closing " is reached.
Note: You can match a single " in your search pattern by double quoting instead "". For instance you can match "Hello" by using the pattern #"""\w+"""

C#, escape double quote not working as expected

I'm trying to escape quotes in an xpath string like so:
var mktCapNode = htmlDoc.DocumentNode.SelectSingleNode("//*[#id=""yfs_j10_a""]");
The actual string I want passed is:
//*[#id="yfs_j10_a"]
This gives a compiler errors: ) expected and ; expected
I'm sure it's simple but I'm stumped. Any ideas?
You need to make this a verbatim string to use the "" as an escape
#"//*[#id=""yfs_j10_a""]"
For a normal string literal you need to use backslashes to escape the double quotes
"//*[#id=\"yfs_j10_a\"]"
Or use the escape char '\':
"//*[#id=\"yfs_j10_a\"]"
In C# the \ character is used to escape (see documentation).
This is different from VB where there are no escape characters except "" which escapes to ".
This means in C# you do not need vbCrLf to start a new line or vbTab to add a tab character to a string. Instead use "\r\n" and "\t".
You can also make the string a literal using the # character, but I do not think this works with the quotation mark.
Add the # prefix to your string.
#"//*[#id=""yfs_j10_a""]"
or escape the quotes with a \
"//*[#id=\"yfs_j10_a\"]"

\tssr>"&\8=f23' as String C#

I have a short question.
I want do put this \tssr>"&\8=f23' into a String (Language C#).
But the compiler always shows an error because for example "\8" is a command.
can someone help me?
Thank you very mutch.
string s = "\\tssr>\"&\\8=f23'";
OR
string s = #"\tssr>""&\8=f23'";
try
string s = #"\tssr>\"&\8=f23";
For double quote[EDIT]
string s = #"\tssr>""&\8=f23";
because \ is special char you need to escape it with either # for \\ as given in below answer
Just write \\8 instead of \8. Or put an # in front of the string. Other characters also need to be escaped with the \ character:
"\\tssr>\"&\\8=f23'"
or this:
#"\tssr>""&\8=f23'"
the backslash \ is used for escaping special characters, like tab or newline. Because of that, the first character also needs to be escaped, because \t is the escape code for Tab.
Try escape sequence
Check this
\\tssr>\"&\\8=f23\'
See below.
var str = "\\tssr>\"&\\8=f23'";
I add a backslash to escape the special characters
The backslash is an escape character in C#, which forms part of an escape sequence.
You have two options: either use TWO backslashes (also known as escaping the backslash) for example var foo = "hello\\world";, or embed the sequence into a string literal eg var foo = #"hello\world";.
Try this:
string s = " \\tssr>\"&\\8=f23' ";

Categories