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
Related
I want to replace /* in selected text with //.
I used regex to do this. When I used any other strings it worked. But when I used:
String result = System.Text.RegularExpressions.Regex.Replace(seltext,"/*","//");
It shows:
/* int a,b; // sample input
///*i//n//t//a//,//b//; // sample output
Instead I want:
// int a,b;
* has a special meaning in regular expressions - it means "match 0 or more of the preceding character/group".
It sounds like you don't want a regex at all - you just want
string result = seltext.Replace("/*", "//");
If you really want to use regular expressions, you need to escape the * (and various other characters, if you use them):
string result = Regex.Replace(seltext, #"/\*", "//");
Note the use of a verbatim string literal (indicated by the the # at the start of the string) to avoid having to escape the \ as well for C# string literal reasons. You'd need to use "/\\*" which isn't as clear. Verbatim string literals are very handy for regular expressions.
I would suggest caution when trying to use simple text operations (including regular expressions) on source code though. For example, imagine applying the replacement to the first of the code snippets above...
Your Question is WHY.... wrong output?
Let's start with the WHY, then we'll look at the fix.
The core of the problem is that /* is able to match the Empty String. Therefore, at Each Position, you insert //
You Need to Escape the Quantifier *
In regex, * means "match what precedes zero or more times".
Therefore, /* does not match /*, but rather, the empty string (zero slashes) or a series of slashes: ////
To match a literal *, escape it with a backslash: \*. Therefore your regex becomes /\*
/* Matches at Every Single Position in the String
Because /* can match the empty string, it matches at every single position.
Therefore, at each position, you insert //, hence your result
In C# Code: Replace not only /* but also /******
There is no need to use regex for a fixed literal /*, so to make it more interesting, we will not only replace /* but /*****. Do do so, we add a + quantifier after the \*. One line is enough:
string resultString = Regex.Replace(s1, #"/\*+", "//");
See this demo to observe how we match at each position.
See this demo to see how to do the replacement.
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");
I want to write something like this C:\Users\UserName\Documents\Tasks in a textbox:
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\Tasks";
I get the error:
Unrecognized escape sequence.
How do I write a backslash in a string?
The backslash ("\") character is a special escape character used to indicate other special characters such as new lines (\n), tabs (\t), or quotation marks (\").
If you want to include a backslash character itself, you need two backslashes or use the # verbatim string:
var s = "\\Tasks";
// or
var s = #"\Tasks";
Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
Generally speaking, most C# .NET developers tend to favour using the # verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.
That all said, in this case, I would actually recommend you use the Path.Combine utility method as in #lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.
To escape the backslash, simply use 2 of them, like this:
\\
If you need to escape other things, this may be helpful..
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
Just escape the "\" by using + "\\Tasks" or use a verbatim string like #"\Tasks"
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";
Put a double backslash instead of a single backslash...
even though this post is quite old I tried something that worked for my case .
I wanted to create a string variable with the value below:
21541_12_1_13\":null
so my approach was like that:
build the string using verbatim
string substring = #"21541_12_1_13\"":null";
and then remove the unwanted backslashes using Remove function
string newsubstring = substring.Remove(13, 1);
Hope that helps.
Cheers
I am using .NET (C#) code to write to a database that interfaces with a Perl application. When a single quote appears in a string, I need to "escape" it. IOW, the name O'Bannon should convert to O\'Bannon for the database UPDATE. However, all efforts at string manipulation (e.g. .Replace) generate an escape character for the backslash and I end up with O\\'Bannon.
I know it is actually generating the second backslash, because I can read the resulting database field's value (i.e. it is not just the IDE debug value for the string).
How can I get just the single backslash in the output string?
R
Well I did
"O'Bannon".Replace("'","\\'")
and result is
"O\'Bannon"
Is this what you want?
You can use "\\", which is the escape char followed by a backslash.
See the list of Escape Sequences here: http://msdn.microsoft.com/en-us/library/h21280bw.aspx
even better assign a var to the replace so that you can check it as well if needed
var RepName = "O'Bannon";
var Repstr = RepName.Replace("'","\\'");
You can also use a verbatim string
s = s.Replace("'", #"\'");
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.