Regex Expression for Finding Words Surrounded By {{ }} - c#

I have a string that has variables inserted within them. They are surround by double curly braces, i.e. {{VARIABLE}}.
What Regex expression could be use to return the variable names within the double curly braces?

You can use lookahead and lookbehind assertions to match text that comes after and before certain patterns. You can also use a negative character class to match characters that aren't }, so that your matched string isn't too greedy.
(?<=\{\{)[^}]+(?=\}\})
You can see this pattern in action here

You could also use a capturing group:
\{\{(.+?)}}
Regex demo
If there can not be anything before or after the placeholder and the placeholder itself can contain a { or } you might use:
(?<!\S)\{\{(.+?)}}(?!\S)
Explanation
(?<!\S) Assert what is on the left is not a non whitespace char
\{\{ Match {{
(.+?) Capture in group 1 matching any char 1+ times non greedy
}} Match literally
(?!\S) Assert what is on the right is not a non whitespace char
Regex demo

Related

Regexp: Match value if condition occurs

I have a string like
Value = ('1 OR 2') OR Value = ('THREE OR FOUR')
and I want to split it by OR (that one is not in quotes).
How can I do it with regexp? It has to match only if I have an even number of quotes before OR.
Is it possible?
I tried use [\w\W]*?'[\w\W]*(\sOR\s) but it works incorrect, it takes only last OR, even if it is inside quotes.
Using [\w\W] can match any character including '
You could make use of lookaround with an infinite quantifier in C# and match optional pairs of single quotes.
If you want all pairs of single quotes in the whole string, you can also assert them to the right.
If you don't want to cross matching newline, you can use [^'\r\n]* instead of [^']*
(?<=^(?:[^']*'[^']*')*[^']*)\bOR\b(?=(?:[^']*'[^']*')*[^']*$)
(?<= Positive lookbehind
^(?:[^']*'[^']*')*[^']* Match optional pairs or single quotes from the start of the string
) Close lookbehind
\bOR\b Match OR between word boundaries
(?= Positive lookahead
(?:[^']*'[^']*')*[^']*$ Match optional pairs of quotes till the end of the string
) Close lookahead
Regex demo
Using a positive lookbehind ensures that OR is only matched if it is preceded by an even number of single quotes (and surrounded by whitespace as in your regex).
(?<=^(?:[^']*'[^']*')*[^']*)\sOR\s
How about trying to match everything that is valid and use Regex.Matches to get all the sub-strings?
var splitRE = new Regex(#"([^'OR]+|O[^R]|'[^']*'|(?<!O)R|(?<=\w)OR|OR(?=\w))+", RegexOptions.Compiled);
var ans = splitRE.Matches(s);
Basically the pattern matches anything not a single-quote, O, or R OR matches O and following not an R OR matches a single-quoted string OR matches an R not preceded by an O OR matches an OR preceded by a word character OR matches an OR followed by a word character.

C# Regex substring should be at start and end but not in the middle

Let's consider ${ the opening tag and }$ the closing tag. The opening tag should only occur at the start and the closing tag. The chars {,},$ are allowed as long as they do not form one of the tags: So ${Macro{Inner}}$ is allowed.
This is what I tried: \$\{[^((\$\{)|(\}\$))]+\}\$
If the curly's don't have to be balances, you might use
(?<!\S)\${[^{}]*(?>(?:(?<!\$){|}(?!\$))[^{}]*)*}\$(?!\S)
The pattern matches:
(?<!\S) Assert a whitespace boundary to the left
\${ match ${
[^{}]* Optionally repeat matching any char other than { and }
(?> Atomic group
(?: Non capture group
(?<!\$){ Match { asserting not { to the left
| Or
}(?!\$) Match } asserting not } to the right
) Close non capture group
[^{}]* Optionally repeat matching any char other than { and }
)* Close the atomic group and optionally repeat
}\$ Match }$
(?!\S) Assert a whitespace boundary to the right
.NET regex demo
If the parenthesis should be balanced, you could use:
(?<!\S)\${(?>(?<!\$){(?<c>)|[^{}]+|}(?!\$)(?<-c>))*(?(c)(?!))}\$(?!\S)
Regex demo
Don't need regex for this
s.StartsWith("${") && s.EndsWith("}$") && new[]{"${", "}$"}.All(x => x.IndexOf(x, 2, s.Length-4) == -1)
Why do I advocate not using a regex?
go for the simple solution, not the perfect one;
this code is more readable/self documenting
it's not so a regex so complicated that you have to ask on SO to make it work
you or the developer that replaces you has a more reasonable chance at maintaining it than a regex of the required complexity
You have tried the pattern [^((\$\{)|(\}\$))]+ to prevent ${ or }$ being matched, but that is a misunderstanding of how character groups work.
[^((\$\{)|(\}\$))] means match a single character that is not a (, $, {, ), |, or }.
The following working regex is an example of how to use a negative lookahead to avoid ${ or }$ being matched:
\$\{(?:(?!\$\{|\}\$).)*\}\$
If you want to match across newlines use RegexOptions.Singleline.
(Although I have done so, it is not necessary to escape the { and } in the regex above because the regex engine can determine from the surrounding context that they should be interpreted as match the literal character.)

Parsing text between quotes with .NET regular expressions

I have the following input text:
#"This is some text #foo=bar #name=""John \""The Anonymous One\"" Doe"" #age=38"
I would like to parse the values with the #name=value syntax as name/value pairs. Parsing the previous string should result in the following named captures:
name:"foo"
value:"bar"
name:"name"
value:"John \""The Anonymous One\"" Doe"
name:"age"
value:"38"
I tried the following regex, which got me almost there:
#"(?:(?<=\s)|^)#(?<name>\w+[A-Za-z0-9_-]+?)\s*=\s*(?<value>[A-Za-z0-9_-]+|(?="").+?(?=(?<!\\)""))"
The primary issue is that it captures the opening quote in "John \""The Anonymous One\"" Doe". I feel like this should be a lookbehind instead of a lookahead, but that doesn't seem to work at all.
Here are some rules for the expression:
Name must start with a letter and can contain any letter, number, underscore, or hyphen.
Unquoted must have at least one character and can contain any letter, number, underscore, or hyphen.
Quoted value can contain any character including any whitespace and escaped quotes.
Edit:
Here's the result from regex101.com:
(?:(?<=\s)|^)#(?<name>\w+[A-Za-z0-9_-]+?)\s*=\s*(?<value>(?<!")[A-Za-z0-9_-]+|(?=").+?(?=(?<!\\)"))
(?:(?<=\s)|^) Non-capturing group
# matches the character # literally
(?<name>\w+[A-Za-z0-9_-]+?) Named capturing group name
\s* match any white space character [\r\n\t\f ]
= matches the character = literally
\s* match any white space character [\r\n\t\f ]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?<value>(?<!")[A-Za-z0-9_-]+|(?=").+?(?=(?<!\\)")) Named capturing group value
1st Alternative: [A-Za-z0-9_-]+
[A-Za-z0-9_-]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
0-9 a single character in the range between 0 and 9
_- a single character in the list _- literally
2nd Alternative: (?=").+?(?=(?<!\\)")
(?=") Positive Lookahead - Assert that the regex below can be matched
" matches the characters " literally
.+? matches any character (except newline)
Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
(?=(?<!\\)") Positive Lookahead - Assert that the regex below can be matched
(?<!\\) Negative Lookbehind - Assert that it is impossible to match the regex below
\\ matches the character \ literally
" matches the characters " literally
You can use a very useful .NET regex feature where multiple same-named captures are allowed. Also, there is an issue with your (?<name>) capture group: it allows a digit in the first position, which does not meet your 1st requirement.
So, I suggest:
(?si)(?:(?<=\s)|^)#(?<name>\w+[a-z0-9_-]+?)\s*=\s*(?:(?<value>[a-z0-9_-]+)|(?:"")?(?<value>.+?)(?=(?<!\\)""))
See demo
Note that you cannot debug .NET-specific regexes at regex101.com, you need to test them in .NET-compliant environment.
Use string methods.
Split
string myLongString = ""#"This is some text #foo=bar #name=""John \""The Anonymous One\"" Doe"" #age=38"
string[] nameValues = myLongString.Split('#');
From there either use Split function with "=" or use IndexOf("=").

Regular Expression for no repeating special characters (C#)

I am new to regular expressions and need a regular expression for address, in which user cannot enter repeating special characters such as: ..... or ,,,.../// etc and none of the special characters could be entered more than 5 times in the string.
...,,,....// =>No Match
Street no. 40. hello. =>Match
Thanks in advance!
I have tried this:
([a-zA-Z]+|[\s\,\.\/\-]+|[\d]+)|(\(([\da-zA-Z]|[^)^(]+){1,}\))
It selects all alphanumeric n some special character with no empty brackets.
You can use Negative lookahead construction that asserts what is invalid to match. Its format is (?! ... )
For your case you can try something like this:
This will not match the input string if it has 2 or more consecutive dots, commas or slashes (or any combination of them)
(?!.*[.,\/]{2}) ... rest of the regex
This will not match the input string if it has more than 5 characters 'A'.
(?!(.*A.*){5}) ... rest of the regex
This will match everything except your restrictions. Repplace last part (.*) with your regex.
^(?!.*[.,\/]{2})(?!(.*\..*){5})(?!(.*,.*){5})(?!(.*\/.*){5}).*$
Note: This regex may no be optimized. It may be faster if you use loop to iterate over string characters and count their occurences.
You can use this regex:
^(?![^,./-]*([,./-])\1)(?![^,./-]*([,./-])(?:[^,./-]*\2){4})[ \da-z,./-]+$
In C#:
foundMatch = Regex.IsMatch(yourString, #"^(?![^,./-]*([,./-])\1)(?![^,./-]*([,./-])(?:[^,./-]*\2){4})[ \da-z,./-]+$", RegexOptions.IgnoreCase);
Explanation
The ^ anchor asserts that we are at the beginning of the string
The negative lookahead (?![^,./-]*([,./-])\1) asserts that it is not possible to match any number of special chars, followed by one special char (captured to Group 1) followed by the same special char (the \1 backreference)
The negative lookahead (?![^,./-]*([,./-])(?:[^,./-]*\2){4}) ` asserts that it is not possible to match any number of special chars, followed by one special char (captured to Group 2), then any non-special char and that same char from Group 2, four times (five times total)
The $ anchor asserts that we are at the end of the string
A regular expression string to detect invalid strings is:
[^\w \-\r\n]{2}|(?:[\w \-]+[^\w \-\r\n]){5}
As C# string literal (regular and verbatim):
"[^\\w \\-\\r\\n]{2}|(?:[\\w \\-]+[^\\w \\-\\r\\n]){5}"
#"[^\w \-\r\n]{2}|(?:[\w \-]+[^\w \-\r\n]){5}"
It is much easier to find a string than to validate if a string does not contain ...
It can be checked with this expression if the string entered by the user is invalid because of a match of 2 special characters in sequence OR 5 special characters used in the string.
Explanation:
[^...] ... a negative character class definition which matches any character NOT being one of the characters listed within the square brackets.
\w ... a word character which is either a letter, a digit or an underscore.
The next character is simply a space character.
\- ... the hyphen character which must be escaped with a backslash within square brackets as otherwise the hyphen character would be interpreted as "FROM x TO z" (except when being the first or the last character within the square brackets).
\r ... carriage return
\n ... line-feed
Therefore [^\w \-\r\n] finds a character which is NOT a letter, NOT a digit, NOT an underscore, NOT a space, NOT a hyphen, NOT a carriage return and also NOT a line-feed.
{2} ... the preceding expression must match 2 such characters.
So with the expression [^\w \-\r\n]{2} it can be checked if the string contains 2 special characters in a sequence which makes the string invalid.
| ... OR
(?:...) ... none marking group needed here for applying the expression inside with the multiplier {5} at least 5 times.
[...] ... a positive character class definition which matches any character being one of the characters listed within the square brackets.
[\w \-]+ ... find a word character, or a space, or a hyphen 1 or more times.
[^\w \-\r\n] ... and next character being NOT a word character, space, hyphen, carriage return or line-feed.
Therefore (?:[\w \-]+[^\w \-\r\n]){5} finds a string with 5 "special" characters between "standard" characters.

Trying to understand this regex

I have this regex
^(\\w|#|\\-| |\\[|\\]|\\.)+$
I'm trying to understand what it does exactly but I can't seem to get any result...
I just can't understand the double backslashes everywhere... Isn't double backslash supposed to be used to get a single backslash?
This regex is to validate that a username doesn't use weird characters and stuff.
If someone could explain me the double backslashes thing please. #_#
Additional info: I got this regex in C# using Regex.IsMatch to check if my username string match the regex. It's for an asp website.
My guess is that it's simply escaping the \ since backslash is the escape character in c#.
string pattern = "^(\\w|#|\\-| |\\[|\\]|\\.)+$";
Can be rewritten using a verbatim string as
string pattern = #"^(\w|#|\-| |\[|\]|\.)+$";
Now it's a bit easier to understand what's going on. It will match any word character, at-sign, hyphen, space, square bracket or period, repeated one or more times. The ^ and $ match the begging and end of the string, respectively, so only those characters are allowed.
Therefore this pattern is equivalent to:
string pattern = #"^([\w# \[\].-])+$";
Double slash are supposed to be single slash. Double slash are used to escape the slash itself, as slashes are used for other escape characters in C# String context e.g. \n stands for new line
With double slashes sorted out, it becomes ^(\w|#|\-| |\[|\]|\.)+$
Break down this regex, as | means OR, and \w|#|\-| |\[|\]|\. would mean \w or # or \- or space or \[ or \] or \.. That is, any alphanumeric character, #, -, space, [, ] and . characters. Note that this slash is regex escape, to escape -, [, ] and . characters as they all have special meanings in regex context
And, + means the previous token (i.e. \w|#|\-| |\[|\]|\.) repeated one or more times
So, the entire thing means one or more of any combination of alphanumeric character, #, -, space, [, ] and . characters.
There are online tools to analyze regexes. Once such is at http://www.myezapp.com/apps/dev/regexp/show.ws
where it reports
Sequence: match all of the followings in order
BeginOfLine
Repeat
CapturingGroup
GroupNumber:1
OR: match either of the followings
WordCharacter
#
-
[
]
.
one or more times
EndOfLine
As others have noted, the double backslashes just escape a backslash so you can embed the regex in a string. For example, "\\w" will be interpreted as "\w" by the parser.
^ means beginning of the line.
the parentheses is use for grouping
\w is a word character
| means OR
# match the # character
\- match the hyphen character
[ and ] matches the squares brackets
\. match a period
+ means one or more
$ the end of line.
So the regex is use to match a string which contains only word characters or an # or an hyphen or a space or squares brackets or a dot.
Here's what it means:
^(\\w|#|\\-| |\\[|\\]|\\.)+$
^ - Means the regex starts at the beginning of the string. The match shouldn't start in the middle of the string.
Here's the individual things in the parentheses:
\\w - Indicates a "word" character. Normally, this is shown as \w, but this is being escaped.
# - Indicates an # symbol is allowed
\\- - Indicates a - is allowed. This is escaped since the dash can have other meanings in regex. Since it's not in a character class, I don't believe this is technically needed.
- A space is allowed
\\[ and \\] - [ and ] are allowed.
\\. - A period is a valid character. Escaped because periods have special meanings in regex.
Now all of those characters have | as delimiters in the parentheses - this means OR. So any of those characters are valid.
The + at the end means one or more characters as described in parentheses are valid. The $ means the end of the regex must match the end of the string.
Note that the double slashes aren't necessary if you just prefix the string like this:
#"\w" is the same as "\\w"

Categories

Resources