c# Regex, how can I escape [[ and ]] [duplicate] - c#

This question already has answers here:
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
I'm trying to instantiate a new Regex class with the regular expression
var reg = new Regex("[[" + token.Key + "]]");
But I'm getting the following error
System.ArgumentException: 'parsing "[[Impact]]" - [x-y] range in reverse order.'
How can I instantiate the new class with the double square brackets in the regular expression?

You could use built-in functions to escape things:
var re = Regex.Escape("[[") + token.Key + Regex.Escape("]]");
var reg = new Regex(re);
But you may also want to escape the token.Key?
Or just use a string.Contains(...), if you don't want the special features of regex.

You need to escape the characters "[" and "]" for the regular expression, and if you are using "\" to escape the brackets, then you need to escape those in your C# string as well.
That means it can be either:
"\\[\\[" + key + "]]"
or
#"\[\[" + key + "]]"
or
Regex.Escape("[[") + key + "]]"
You don't need to escape the latter "]" because Regex recognizes them as normal characters if you don't have an unescaped "[" before them. I tried it on Regexpal (a regex testing website) and other answers suggest it as well.

This one works:
var reg = new Regex(#"\[\[" + token.Key + #"]]");
(Note: the second # is not actually needed)
Update:
This is even better:
var reg = new Regex($#"\[\[{token.Key}]]");

Just escape every bracket with a bracket like is shown below:
var reg = new Regex("[[[["+ token.Key +"]]]]");

Try
var reg = new Regex("[[][[]" + token.Key + "[]][]]");
it will match, for example [[Impact]] if token.Key equals "Impact".

Related

mvc regex replace array of pattern on one sentence [duplicate]

This question already has answers here:
Why \b does not match word using .net regex
(2 answers)
Closed 5 years ago.
I want to replace certain words in one sentence string with regex replace.
For it, I create pattern array :
string[] words = {"abc","132","qwe","bold","test"};
and for replace, I do it :
foreach (string item in words){
output = Regex.Replace(output,#"\b" + item + "\b", " ");
}
but this way don't work ...
Someone has an idea?
Explanation
I use the above method in VB.net and will respond without problems.
I am a beginner in C #
It looks like you forgot the # literal at the second \b:
either put it in there
output = Regex.Replace(output, #"\b" + item + #"\b", " ");
or double the backslash so it is used as an escape character:
output = Regex.Replace(output, #"\b" + item + "\\b", " ");

Building dynamic Regex in C# [duplicate]

This question already has answers here:
What characters need to be escaped in .NET Regex?
(4 answers)
Closed 7 years ago.
I use dynamically built regex. Problem is when symbol = "aaaa (1)" because regex tries to parse it, but I want to treat it literary
Regex regex = new Regex(#"(^" + "/(" + symbol + #" \(\d+\)$)|" + symbol);
You need to escape special chars:
var escapedSymbol = Regex.Escape(symbol);
Regex regex = new Regex(#"(^" + "/(" + escapedSymbol + #" \(\d+\)$)|" + escapedSymbol );
Reffer: msdn

How to write string with many characters [, > etc without writing it singly [duplicate]

This question already has answers here:
Escape double quotes in a string
(9 answers)
Closed 8 years ago.
I have a problem, because everytime i need to write indexof, i need to use +
for example:
String lsdfrom2 = '[' + '"' + "LSD" + ',' + '[' + ']' + ',' + '{' + '"' + "token" + '"' + ":" + '"';
How to write it in another way? thats soo anoying to write it like in example
I mean, how to read text below without write every char singly
["LSD",[],{"token":"
Write it as a string (escaping the quotes is required via \")
String lsdfrom2 = "[\"LSD\",[],{\"token\":\""
Write is as a string literal with " to escape the quotes.
string mystring = #"[""LSD"",[],{""token"":""";
I believe you are looking to escape the quotation marks?
string lsdfrom2 = "[\"LSD\",[],{\"token\":\"";
See: Escape Sequences
You need to escape the quotes
String lsdfrom2 = "[\"LSD\",[],{\"token\":\"" // escaping the quotes..

Using RegEx to ignore empty strings and spaces

I have the following simple test which doesnt return true for some reason.
string[] test = new string[] { "A", " ", " ", "D", "" };
Regex reg = new Regex(#"^[A-Z]\s$");
bool ok = test.All(x => reg.IsMatch(x));
I've also tried putting the \s inside the square brackets but that doesn't work either
I want to make sure that all characters in the array that are not empty or blank spaces match A-Z.
I realise I could do a Where(x=>!String.IsNullorEmpty(x) && x != " ") before the All but I thought Regex could handle this scenario
I think you want:
Regex reg = new Regex(#"^[A-Z\s]*$");
That basically says "the string consists entirely of whitespace or A-Z".
If you want to force it to be a single character or empty, just change it to:
Regex reg = new Regex(#"^[A-Z\s]?$");
Enumerable.All<TSource> Method Determines whether all elements of a sequence satisfy a condition.
The regular expression ^[A-Z]\s$ says: two-character string, whose first character is A-Z and the second is a white space. What you actually want is ^[A-Z\s]*$.

Replace multiple lines with .net Regex

I am new to stackoverflow (my first post) and regex.
Currently i am working on a simple dirty app to replace baseclass properties with ctor injected fields. (cos i need to edit about 400 files)
It should find this:
ClassName(WiredObjectRegistry registry) : base(registry)
{
and replace with:
ClassName(IDependency paramName, ISecondDependency secondParam, ... )
{
_fieldName = paramName;
...
so i need to replace the two old lines with three or more new lines.
basically i was thinking:
find this ->
className + ctorParams + zero or more
whitespaces + newline + zero or more
whitespaces + {
replace with ->
className + newCtorParams + newline +
{
my field assignments
i tried this regex for .net
className + ctorParam + #"\w*" + "\r|\n" + #"\w*" + #"\{"
which does not replace the "{" and the whitespaces correctly
the replaced file content looks like this:
public CacheManager(ICallManager callManager, ITetraEventManager tetraEventManager, IConferenceManager conferenceManager, IAudioManager audioManager)
{
_callManager = callManager;
_tetraEventManager = tetraEventManager;
_conferenceManager = conferenceManager;
_audioManager = audioManager;
{
can u please help me with this :-|
david
If you're translating
className + ctorParams + zero or more whitespaces + newline + zero or more whitespaces + {
into regex as
className + ctorParam + #"\w*" + "\r|\n" + #"\w*" + #"\{"
then you're making several errors.
First, the character class for whitespace is \s. \w means "alphanumeric character".
Second, "\r|\n" will result in the alternation operator | separating the entire regex in two alternative parts (= "match either the regex before the | or the regex after the |"). In your case, you don't need this bit at all since \s will already match spaces, tabs and newlines. If you do want a regex that matches a Unix, Mac or DOS newline, use \r?\n?.
But, as the comments show, unless you show us what you really want to do, we can't help you further.

Categories

Resources