Regex.Escape() unrecognized exception - c#

I have the following code in C#:
String str = #"\hello ali how are you? are you fine? hello and hi";
Console.WriteLine(Regex.Matches(Regex.Escape(str), #"\hello").Count);
I get the following error:
{"parsing \"\hello\" - Unrecognized escape sequence \h."}
I need to know when a \ + (some names) exists in my code. I have used # for not using escape sequence characters but I still get the mentioned error. I can not understand why this happens!

\ is used to denote shorthand classes in a regular expression. e.g. \d means "any digit", or \w means "any word character (alphanumeric characters plus underscores)". The regex engine thinks you're trying to use \h as one of these shorthand sequences, but it's not a valid one.
To match a literal \ in the regex you need to escape it with another one, e.g. \\. So in your example your regex would be \\hello.
See http://www.regular-expressions.info/characters.html for more detailed information.

Escape sequences are used independently in both Strings and regular expressions with different meanings. When you prefix the string literal with # you are telling the compiler to interpret the string literally without escape sequences. However the Regular Expression engine again sees the "\h" and tries to interpret as an escape sequence.
Basically you need to apply both the String literal # and the Regex.Escape function to make the \h be interpreted as a literal by both parsers:
Console.WriteLine(Regex.Matches(str, Regex.Escape(#"\hello")).Count);

Related

RegEx expression works on regex101 but not in C# [duplicate]

https://regex101.com/r/sB9wW6/1
(?:(?<=\s)|^)#(\S+) <-- the problem in positive lookbehind
Working like this on prod: (?:\s|^)#(\S+), but I need a correct start index (without space).
Here is in JS:
var regex = new RegExp(/(?:(?<=\s)|^)#(\S+)/g);
Error parsing regular expression: Invalid regular expression:
/(?:(?<=\s)|^)#(\S+)/
What am I doing wrong?
UPDATE
Ok, no lookbehind in JS :(
But anyways, I need a regex to get the proper start and end index of my match. Without leading space.
Make sure you always select the right regex engine at regex101.com. See an issue that occurred due to using a JS-only compatible regex with [^] construct in Python.
JS regex - at the time of answering this question - did not support lookbehinds. Now, it becomes more and more adopted after its introduction in ECMAScript 2018. You do not really need it here since you can use capturing groups:
var re = /(?:\s|^)#(\S+)/g;
var str = 's #vln1\n#vln2\n';
var res = [];
while ((m = re.exec(str)) !== null) {
res.push(m[1]);
}
console.log(res);
The (?:\s|^)#(\S+) matches a whitespace or the start of string with (?:\s|^), then matches #, and then matches and captures into Group 1 one or more non-whitespace chars with (\S+).
To get the start/end indices, use
var re = /(\s|^)#\S+/g;
var str = 's #vln1\n#vln2\n';
var pos = [];
while ((m = re.exec(str)) !== null) {
pos.push([m.index+m[1].length, m.index+m[0].length]);
}
console.log(pos);
BONUS
My regex works at regex101.com, but not in...
First of all, have you checked the Code Generator link in the Tools pane on the left?
All languages - "Literal string" vs. "String literal" alert - Make sure you test against the same text used in code, literal string, at the regex tester. A common scenario is copy/pasting a string literal value directly into the test string field, with all string escape sequences like \n (line feed char), \r (carriage return), \t (tab char). See Regex_search c++, for example. Mind that they must be replaced with their literal counterparts. So, if you have in Python text = "Text\n\n abc", you must use Text, two line breaks, abc in the regex tester text field. Text.*?abc will never match it although you might think it "works". Yes, . does not always match line break chars, see How do I match any character across multiple lines in a regular expression?
All languages - Backslash alert - Make sure you correctly use a backslash in your string literal, in most languages, in regular string literals, use double backslash, i.e. \d used at regex101.com must written as \\d. In raw string literals, use a single backslash, same as at regex101. Escaping word boundary is very important, since, in many languages (C#, Python, Java, JavaScript, Ruby, etc.), "\b" is used to define a BACKSPACE char, i.e. it is a valid string escape sequence. PHP does not support \b string escape sequence, so "/\b/" = '/\b/' there.
All languages - Default flags - Global and Multiline - Note that by default m and g flags are enabled at regex101.com. So, if you use ^ and $, they will match at the start and end of lines correspondingly. If you need the same behavior in your code check how multiline mode is implemented and either use a specific flag, or - if supported - use an inline (?m) embedded (inline) modifier. The g flag enables multiple occurrence matching, it is often implemented using specific functions/methods. Check your language reference to find the appropriate one.
line-breaks - Line endings at regex101.com are LF only, you can't test strings with CRLF endings, see regex101.com VS myserver - different results. Solutions can be different for each regex library: either use \R (PCRE, Java, Ruby) or some kind of \v (Boost, PCRE), \r?\n, (?:\r\n?|\n)/(?>\r\n?|\n) (good for .NET) or [\r\n]+ in other libraries (see answers for C#, PHP). Another issue related to the fact that you test your regex against a multiline string (not a list of standalone strings/lines) is that your patterns may consume the end of line, \n, char with negated character classes, see an issue like that. \D matched the end of line char, and in order to avoid it, [^\d\n] could be used, or other alternatives.
php - You are dealing with Unicode strings, or want shorthand character classes to match Unicode characters, too (e.g. \w+ to match Стрибижев or Stribiżew, or \s+ to match hard spaces), then you need to use u modifier, see preg_match() returns 0 although regex testers work - To match all occurrences, use preg_match_all, not preg_match with /...pattern.../g, see PHP preg_match to find multiple occurrences and "Unknown modifier 'g' in..." when using preg_match in PHP?- Your regex with inline backreference like \1 refuses to work? Are you using a double quoted string literal? Use a single-quoted one, see Backreference does not work in PHP
phplaravel - Mind you need the regex delimiters around the pattern, see https://stackoverflow.com/questions/22430529
python - Note that re.search, re.match, re.fullmatch, re.findall and re.finditer accept the regex as the first argument, and the input string as the second argument. Not re.findall("test 200 300", r"\d+"), but re.findall(r"\d+", "test 200 300"). If you test at regex101.com, please check the "Code Generator" page. - You used re.match that only searches for a match at the start of the string, use re.search: Regex works fine on Pythex, but not in Python - If the regex contains capturing group(s), re.findall returns a list of captures/capture tuples. Either use non-capturing groups, or re.finditer, or remove redundant capturing groups, see re.findall behaves weird - If you used ^ in the pattern to denote start of a line, not start of the whole string, or used $ to denote the end of a line and not a string, pass re.M or re.MULTILINE flag to re method, see Using ^ to match beginning of line in Python regex
- If you try to match some text across multiple lines, and use re.DOTALL or re.S, or [\s\S]* / [\s\S]*?, and still nothing works, check if you read the file line by line, say, with for line in file:. You must pass the whole file contents as the input to the regex method, see Getting Everything Between Two Characters Across New Lines. - Having trouble adding flags to regex and trying something like pattern = r"/abc/gi"? See How to add modifers to regex in python?
c#, .net - .NET regex does not support possessive quantifiers like ++, *+, ??, {1,10}?, see .NET regex matching digits between optional text with possessive quantifer is not working - When you match against a multiline string and use RegexOptions.Multiline option (or inline (?m) modifier) with an $ anchor in the pattern to match entire lines, and get no match in code, you need to add \r? before $, see .Net regex matching $ with the end of the string and not of line, even with multiline enabled - To get multiple matches, use Regex.Matches, not Regex.Match, see RegEx Match multiple times in string - Similar case as above: splitting a string into paragraphs, by a double line break sequence - C# / Regex Pattern works in online testing, but not at runtime - You should remove regex delimiters, i.e. #"/\d+/" must actually look like #"\d+", see Simple and tested online regex containing regex delimiters does not work in C# code - If you unnecessarily used Regex.Escape to escape all characters in a regular expression (like Regex.Escape(#"\d+\.\d+")) you need to remove Regex.Escape, see Regular Expression working in regex tester, but not in c#
dartflutter - Use raw string literal, RegExp(r"\d"), or double backslashes (RegExp("\\d")) - https://stackoverflow.com/questions/59085824
javascript - Double escape backslashes in a RegExp("\\d"): Why do regex constructors need to be double escaped?
- (Negative) lookbehinds unsupported by most browsers: Regex works on browser but not in Node.js - Strings are immutable, assign the .replace result to a var - The .replace() method does change the string in place - Retrieve all matches with str.match(/pat/g) - Regex101 and Js regex search showing different results or, with RegExp#exec, RegEx to extract all matches from string using RegExp.exec- Replace all pattern matches in string: Why does javascript replace only first instance when using replace?
javascriptangular - Double the backslashes if you define a regex with a string literal, or just use a regex literal notation, see https://stackoverflow.com/questions/56097782
java - Word boundary not working? Make sure you use double backslashes, "\\b", see Regex \b word boundary not works - Getting invalid escape sequence exception? Same thing, double backslashes - Java doesn't work with regex \s, says: invalid escape sequence - No match found is bugging you? Run Matcher.find() / Matcher.matches() - Why does my regex work on RegexPlanet and regex101 but not in my code? - .matches() requires a full string match, use .find(): Java Regex pattern that matches in any online tester but doesn't in Eclipse - Access groups using matcher.group(x): Regex not working in Java while working otherwise - Inside a character class, both [ and ] must be escaped - Using square brackets inside character class in Java regex - You should not run matcher.matches() and matcher.find() consecutively, use only if (matcher.matches()) {...} to check if the pattern matches the whole string and then act accordingly, or use if (matcher.find()) to check if there is a single match or while (matcher.find()) to find multiple matches (or Matcher#results()). See Why does my regex work on RegexPlanet and regex101 but not in my code?
scala - Your regex attempts to match several lines, but you read the file line by line (e.g. use for (line <- fSource.getLines))? Read it into a single variable (see matching new line in Scala regex, when reading from file)
kotlin - You have Regex("/^\\d+$/")? Remove the outer slashes, they are regex delimiter chars that are not part of a pattern. See Find one or more word in string using Regex in Kotlin - You expect a partial string match, but .matchEntire requires a full string match? Use .find, see Regex doesn't match in Kotlin
mongodb - Do not enclose /.../ with single/double quotation marks, see mongodb regex doesn't work
c++ - regex_match requires a full string match, use regex_search to find a partial match - Regex not working as expected with C++ regex_match - regex_search finds the first match only. Use sregex_token_iterator or sregex_iterator to get all matches: see What does std::match_results::size return? - When you read a user-defined string using std::string input; std::cin >> input;, note that cin will only get to the first whitespace, to read the whole line properly, use std::getline(std::cin, input); - C++ Regex to match '+' quantifier - "\d" does not work, you need to use "\\d" or R"(\d)" (a raw string literal) - This regex doesn't work in c++ - Make sure the regex is tested against a literal text, not a string literal, see Regex_search c++
go - Double backslashes or use a raw string literal: Regular expression doesn't work in Go - Go regex does not support lookarounds, select the right option (Go) at regex101.com before testing! Regex expression negated set not working golang
groovy - Return all matches: Regex that works on regex101 does not work in Groovy
r - Double escape backslashes in the string literal: "'\w' is an unrecognized escape" in grep - Use perl=TRUE to PCRE engine ((g)sub/(g)regexpr): Why is this regex using lookbehinds invalid in R?
oracle - Greediness of all quantifiers is set by the first quantifier in the regex, see Regex101 vs Oracle Regex (then, you need to make all the quantifiers as greedy as the first one)] - \b does not work? Oracle regex does not support word boundaries at all, use workarounds as shown in Regex matching works on regex tester but not in oracle
firebase - Double escape backslashes, make sure ^ only appears at the start of the pattern and $ is located only at the end (if any), and note you cannot use more than 9 inline backreferences: Firebase Rules Regex Birthday
firebasegoogle-cloud-firestore - In Firestore security rules, the regular expression needs to be passed as a string, which also means it shouldn't be wrapped in / symbols, i.e. use allow create: if docId.matches("^\\d+$").... See https://stackoverflow.com/questions/63243300
google-data-studio - /pattern/g in REGEXP_REPLACE must contain no / regex delimiters and flags (like g) - see How to use Regex to replace square brackets from date field in Google Data Studio?
google-sheets - If you think REGEXEXTRACT does not return full matches, truncates the results, you should check if you have redundant capturing groups in your regex and remove them, or convert the capturing groups to non-capturing by add ?: after the opening (, see Extract url domain root in Google Sheet
sed - Why does my regular expression work in X but not in Y?
word-boundarypcrephp - [[:<:]] and [[:>:]] do not work in the regex tester, although they are valid constructs in PCRE, see https://stackoverflow.com/questions/48670105
snowflake-cloud-data-platform snowflake-sql - If you are writing a stored procedure, and \\d does not work, you need to double them again and use \\\\d, see REGEX conversion of VARCHAR value to DATE in Snowflake stored procedure using RLIKE not consistent.

Add special characters to alphanumeric regex

Brand new to using Regular Expressions. I have one that currently accepts alphanumeric characters only. I need to add the following special characters to the regex:
# #$%*():;"',/? !+=-_
Here is the regular expression:
RegularExpression(#"^[a-zA-Z\s.,0-9-]{1,30}$",
When I try to add the special characters, I alter the Regex like so:
RegularExpression(#"^[a-zA-Z\s.,0-9-# #$%*():;"',/? !+=-_]{1,30}$"
However this throws an error starting with the ' character that says Newline in constant.
I've tied to escape both the " and the ' characters, however without any luck.
the problem comes from the double quote that need to be escaped (""), not from the single quote.
#"^[a-zA-Z\s.,0-9##$%*():;""'/?!+=_-]{1,30}$"
note that the - must be at the last (or first) position in a character class, since it has a special meaning (define ranges)
These regexs' are equivalent to yours.
Both use tilde ~ as the delimeter.
Both use double quotes on the regex strings.
Note that in order for the the dash - in class to be interpreted literally and not as a range operator, it must exist somewhere disambiguous, or be escaped.
A good place to put it is between valid ranges (or at the beginning or end of a class).
For example [a-z-0-9] is a good place.
Edit - '-' Literal may have to be escaped or beginning/end of class. (This case was for Perl/PCRE engines)
This one ^[a-z-A-Z0-9_\s.,##$%*():;"',/?!+=]{1,30}$ is your regex without duplicate chars.
To make it more readable noting that the word class is contained, it can be reduced to
^[\w-\s.,##$%*():;"',/?!+=]{1,30}$
Edit - Php test cases removed.

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+"""

Regex.IsMatch() not recognizing escape sequence?

I'm doing a match comparison on some escaped strings:
Regex.IsMatch("\\Application.evtx", "DebugLogs\\ConfigurationServices.log");
I don't see why I'm getting:
"parsing "DebugLogs\ConfigurationServices.log" - Unrecognized escape sequence \C."
The \C is escaped?
The edit really fooled a lot of people, including me!
'\' is a special character in regular expressions - it effectively is an escape character or denotes an escape sequence.
So the RegEx engine sees DebugLogs*\C*onfigurationServices.log which is, indeed, an unrecognized escape sequence. \A actually is an existing escape sequence.
So you need to escape the escape character. The simplest way to do this is to double the number of slashes used:
Regex.IsMatch("\\\\Application.evtx", "DebugLogs\\\\ConfigurationServices.log");
Which the RegEx engine will see as comparisons betweeen "\\Appplication.evtx" and "DebugLogs\\ConfigurationServices.log" - now the backslash has been escaped and has no special meaning.
Regex.IsMatch(#"\\Application.evtx", #"DebugLogs\\ConfigurationServices.log");
works fine too and is more readable.
The \ character is the escape character in strings. For example if you'd like to do a carriage return, you'd use \r. To get around this either use literal strings
#"\Application.evtx"
Or escape the escape character
"\\Application.evtx"
You probably want
Regex.IsMatch(#"\Application.evtx", #"DebugLogs\ConfigurationServices.log");
without the "#" C# will treat \C as an escape sequence similar to the way it would convert \n in to a newline character however \C is not a recognised/valid escape sequence.

C# won't escape "\"? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to use “\” in a string without making it an escape sequence - C#?
Why is it giving me an error in C# when I use a string like: "\themes\default\layout.png"? At the "d" and "l" location? It says unrecognized escape sequence. And how do I stop it from giving me an error when I use: "\"?
Thans
You need to escape it with an additional \:
string value = "\\themes\\default\\layout.png";
or use the # symbol:
string value = #"\themes\default\layout.png";
which will avoid you from doubling all \.
Or if you are dealing with paths (which is what it seems you are) you could use the Path.Combine method:
string value = Path.Combine(#"\", "themes", "default", "layout.jpg");
You're using a backslash to escape 't' and 'd'. If you want to escape the actual backslash you need to do so:
"\\themes\\default\\layout.png"
"Regular" string literals treat the \ character as a special character, used for escape sequences to insert quickly special characters in strings - \n, for example, is used to insert the newline character, \" is used to insert the " character without terminating the string, and so on.
Because of this, to insert a backslash into a "normal" string you have to insert the corresponding escape sequence, which, unsurprisingly, is \\; you would then write in your case:
"\\themes\\default\\layout.png"
Failing to escape the backslashes will result in weird results or errors like the ones you got, since the compiler will try to interpret the couple backslash-letter that follows it as an escape sequence; if such sequence is defined you'll get unwanted characters (e.g. the first \t is escaped to a tab character), if it's not (like \l) you'll get an error about an undefined escape sequence.
Another option, if you don't need to escape any character, is to use the so-called "verbatim" strings literals: if you prefix the string with an # character the escape sequences will be disabled, and the string you write will be taken verbatim by the compiler. The only exception to this rule is for quotes, that can be inserted inside the verbatim string via the "quote escape sequence", i.e. "". In your case you would write:
#"\themes\default\layout.png"
For more info about regular vs verbatim string literals have a look at their documentation.
The backslash is treated as an escape character. Either escape the backslash itslef in the string like so:
"\\themes\\default\\layout.png"
or disable escaping altogether using a verbatim string literal:
#"\themes\default\layout.png"

Categories