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.
Related
I would like to have a regular expression that checks if a string contains upper and lowercase letters, numbers, and underscores as well as a character limit. These are the only Types allowed in the string.
However, the string does not have to contain all of the specified arguments.
Meaning that the string could be alphanumeric or alphanumeric with underscores or just numbers or just letters ETC.
I followed the suggestions provided here: Regular Expression for alphanumeric and underscores
and came up with the following Expression: ^([a-zA-Z0-9_]){3,15}$
So the Question is: What Is wrong with my REGEX?
Your regex - ^([a-zA-Z0-9_]){3,15}$ - matches a whole string that is 3 to 15 chars long and only consists of ASCII letters, digits or _ symbol.
It appears you want to detect a string that contains at least 3 characters from the specified ranges (letter/digit/underscore).
You may use
[a-zA-Z0-9_](?:[^a-zA-Z0-9_]*[a-zA-Z0-9_]){2}
Or a less linear:
(?:[^a-zA-Z0-9_]*[a-zA-Z0-9_]){3}
Use the patterns with Regex.IsMatch, this method allows partial matches.
Details:
[a-zA-Z0-9_] - matches a single char from the ranges specified
(?: - start of a non-capturing group matching a sequence of....
[^a-zA-Z0-9_]* - 0+ chars other than those defined in the negated character class
[a-zA-Z0-9_] - a char from the ranges specified
){2} - ....2 times exactly.
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("=").
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"
I am reading in a file and verifying the contents of the file by checking each line. The string lines look like this:
CMD: [THIS_IS_THE_CMD]
DELAY: [5]
FLAGS: [ANY]
All I need to check is that the line follows that exact form and what is in between the brackets is either text (I have tried [A-Z_] but it's not working) or a number depending on the line.
What I have so far:
string line = "CMD: [THIS_IS_THE_CMD]";
if(!VerifyLine(#"^CMD: \[", line))
{
// No match, set error
}
private static bool VerifyLine(string regExp, string line)
{
Regex reg = new Regex(regExp);
return reg.IsMatch(line);
}
But this does not check the contents in between the brackets and it does not check for the closing bracket.
This should do it for you:
([A-Z_]*):\s*\[(\w*)\]
First group matches the part before the colon, second matches the part inside the []s.
First part can be any uppercase letter or underscore, second part can be any alphanumeric character of any case, or an underscore.
Additionally, you might use the following extras, which require the option that makes ^$ match EOLs instead of just BOF and EOF:
^([A-Z_]*):\s*\[(\w*)\]$ // will only match whole lines
^\s*([A-Z_]*):\s*\[(\w*)\]\s*$ // same as above but ignores extra whitespace
// on the beginning and end of lines
Different things you might use to capture the groups depending on your file format:
[A-Z] // matches any capital letter
[A-Za-z] // matches any letter
[A-Za-z0-9] // matches any alphanumeric character
\w // matches any "word character", which is any alnum character or _
try with this: ^\w+:\s*\[(\w+)\], \w will match alphabet, digit, and underscore
and another pattern will match upper case only: ^[A-Z\d_]+:\s*\[([A-Z\d_]+)\]
You tried ^CMD: \[, but your Regex contains Space. note that in regex you have to use \s to matching white spaces. try your regex but using \s:
if(!VerifyLine(#"^CMD:\s*\[", line))
...
explain:
\s Matches any white-space character.
* Matches the previous element zero or more times.
I have a string that must be on the following format:
XXXX-XX-XXX-XXXX-XXXXXXXXXX-X
where X is an integer. The number of integers don't matter. I just need to make sure that the string:
starts and ends with an integer
contains only integers separated by dashes
what would be the easiest way to validate that?
This regexp should do the trick. It uses a negative lookbehind to avoid matching multiple dashes in a row.
^\d(\d|(?<!-)-)*\d$|^\d$
^ ^ ^ ^
| | | -- is a single digit, or
| | ------- ends with a digit
| ----------------consists on digits or dashes not preceded by dashes
---------------------starts with a digit
Here is a C# code that illustrates its use (also on ideone):
var r = new Regex("^\\d(\\d|(?<!-)-)*\\d$|^\\d$");
Console.WriteLine(r.IsMatch("1-2-3"));
Console.WriteLine(r.IsMatch("1-222-3333"));
Console.WriteLine(r.IsMatch("123"));
Console.WriteLine(r.IsMatch("1-2-3-"));
Console.WriteLine(r.IsMatch("1"));
Console.WriteLine(r.IsMatch("-11-2-3-"));
Use a regular expression.
^\d[-0-9]+\d$
This assumes the string is at least three characters long.
Breakdown:
^ - match start of string
\d - match a digit
[ - start of character class containing:
- - a dash
0-9 - 0 to 9
] - end of character class
+ - match one or more of the previous
\d - match a digit
$ - match end of string
You can change the + to * to make 2 digit strings valid, and add an alternation to make 1 digit strings valid as well:
^(\d|\d[-0-9]*\d)$
Note: In .NET, \d will match any Unicode digit (so, for example, Arabic digits will match) - if you don't want that, replace \d with [0-9] in every place.
you can write a regular expression that does the trick.
Than you can use that regular expression to validate your string
^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string.
\ ---->Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below.
\w ----> matches any word character, equivalent to [a-zA-Z0-9]
\W ----> matches any non word character, equivalent to [^a-zA-Z0-9].
\s ----> matches any white space character, equivalent to [\f\n\r\v]
\S----> matches any non-white space characters, equivalent to [^\f\n\r\v]
\d ----> matches any decimal digits, equivalent to [0-9]
\D----> matches any non-digit characters, equivalent to [^0-9]
\a ----> Matches a bell (alarm) \u0007.
\b ----> Matches a backspace \u0008 if in a [] character class; otherwise, see the note following this table.
\t ---->Matches a tab \u0009.
\r ---->Matches a carriage return \u000D.
\v ---->Matches a vertical tab \u000B.
\f ---->Matches a form feed \u000C.
\n ---->Matches a new line \u000A.
\e ---->Matches an escape \u001B
$number ----> Substitutes the last substring matched by group number number (decimal).
${name} ----> Substitutes the last substring matched by a (? ) group.
$$ ----> Substitutes a single "$" literal.
$& ----> Substitutes a copy of the entire match itself.
$` ----> Substitutes all the text of the input string before the match.
$' ----> Substitutes all the text of the input string after the match.
$+ ----> Substitutes the last group captured.
$_ ----> Substitutes the entire input string.
(?(expression)yes|no) ----> Matches yes part if expression matches and no part will be ommited.
more info at
http://geekswithblogs.net/brcraju/archive/2003/10/23/235.aspx
Regular expression is probably the way to go this might help:
http://www.regular-expressions.info/creditcard.html