I'm trying to build a regular expression in c# to check whether a string follow a specific format.
The format i want is: [digit][white space][dot][letters]
For example:
123 .abc follow the format
12345 .def follow the format
123 abc does not follow the format
I write this expression but it not works completelly well
Regex.IsMatch(exampleString, #"^\d+ .")
^ matches the start of the string, and you got it right.
\d+ matches one or more digits, and you got that one right as well.
A space in a regex matches a literal space, so that works too!
However, a . is a wildcard and will match any one character. You will need to escape it with a backslash like this if you want to match a literal period: \..
To match letters now, you can use [a-z]+ right after the period.
#"^\d+ \.[a-z]+"
The dot is a special character in regex, which matches any character (except, typically, newlines). To match a literal ., you need to escape it:
Regex.IsMatch(exampleString, #"^\d+ \.")
If you want to include the condition for the succeeding letters, use:
Regex.IsMatch(exampleString, #"^\d+ \.[A-Za-z]+$")
For you to get yours to match, keep in mind that the period in regular expressions is a special character that will match any character, so you'll need to escape that.
In addition, \s is a match for any white-space character (tabs, line breaks).
^\d+\s+ \..+
(untested)
Related
I would like to create a custom regular expression. Which shall track that the first character of a username should be an alphabet.
Followed by alphanumeric or can have maximum one occurrence of a special character (- or _). I can check for username starts with the alphabet with this ^[a-zA-Z]+$ but not sure what to do to check at most one occurrence of a special character. Any ideas are welcome.
Thanks
From what I understood of your post, you want the following to match.
a-afdsafd
aafdsafd
aafdsa_fd
aafdsa-fd
aAfdsa-FD
And the following to not match:
aa-dsa-fd
aa-dsa_fd
-afdsafd
_afdsafd
Try /^[a-z](?:(?![a-z]+[\-_])[\-_])?[a-z]+(?:(?<![a-z]+[\-_])[\-_]?)[a-z]+?$/i
The i modifier enables case-insensitive matching.
The ^ and $ anchors ensure that the entire string matches our regex.
[a-z] checks that the first character is an alphabet.
(?:(?![a-z]+[\-_])[\-_])?) looks ahead to check that there is no "special character" used later and if there is none, we optionally match one special character.
[a-z]+ Match one or more alphabets.
(?:(?<![a-z]+[\-_])[\-_]?) does the same thing as 4 except it looks behind.
[a-z]+? Optionally match one or more alphabets.
https://regexr.com/3t86l
Edit: I noticed that aAfdsaFd_ should also match. The above does not match this. Slightly modifying #Wiktor Stribiżew's comment, ^[a-zA-Z][a-zA-Z0-9]*(?:[-_][a-zA-Z0-9]*)?$ seems to work fine with all cases. That's cleaner and more efficient. All credit to #Wiktor Stribiżew.
You could match an upper or lowercase character from the start of the string ^[a-zA-Z], match zero or more times alphanumeric [a-zA-Z0-9]* followed by an optional hyphen or underscore [-_]?.
At the end match zero or more times alphanumeric [a-zA-Z0-9]*$ until the end of the string.
^[a-zA-Z][a-zA-Z0-9]*[-_]?[a-zA-Z0-9]*$
I have written a regular expression to match the following criteria
any digit (0-9)
hyphen
whitespace
in any order
length between 10 and 25
([0-9\-\w]{10,25})
I am using it to detect payment card numbers, so this works:
Regex.IsMatch("34343434343434", "([0-9\\-\\w]{10,25})"); // true
But this also works:
Regex.IsMatch("LogMethodComplete", "([0-9\\-\\w]{10,25})"); // true
What am I doing wrong?
This is C#
Take a look at Regular Expression Language - Quick Reference, section Character Classes.
\w matches any word character including underscore, not whitespace.
To match whitespace, you can use \s.
To match digits, you can use \d.
Instead of using \w you can use \d which means digit you could use regex like
"[\d\-\s]{10,25}" to match your criteria
You don't need to check for "words" and this is what \w does
I have a problem with that regular expression [^%()*+-\/=?#[\\]ªº´¿'.]*` .
I want to avoid the characters inside. the regular expression it is working but when I set something like DAVID, SC I can save the form because it has a comma but this character it is not inside the regular expression.
Could you help me please?
You are not accounting for the special meaning of - inside a character class [.....].
You must either place the dash at the very end, or else escape it with a backslash:
[^%()*+\/=?#\[\]ªº´¿'.-]*
In your original regex, +-\/ disallows any characters between + and / in the ASCII table; these are the comma, dot and dash. Your example input contains a comma so the regex did not match all of the input at once.
I have also fixed the escaping for the [] characters from [\\] to \[\], which I presume was a mistake.
Because you're using * in [^%()*+\/=?#[\\]ªº´¿'.-]* with line start/end anchors. * means match 0 or more of preceding group/pattern in character class and your regex can even match an empty string.
Use this regex:
^[^%()*+\/=?#[\\-]ªº´¿'.]+$
PS: Hyphen - should be either or first OR at last position in character class to avoid escaping.
Rubular Demo
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"
What is the regular exp for a text that can't contain any special characters except space?
Because Prajeesh only wants to match spaces, \s will not suffice as it matches all whitespace characters including line breaks and tabs.
A character set that should universally work across all RegEx parsers is:
[a-zA-Z0-9 ]
Further control depends on your needs. Word boundaries, multi-line support, etc... I would recommend visiting Regex Library which also has some links to various tutorials on how Regular Expression Parsing works.
[\w\s]*
\w will match [A-Za-z0-9_] and the \s will match whitespaces.
[\w ]* should match what you want.
Assuming "special characters" means anything that's not a letter or digit, and "space" means the space character (ASCII 32):
^[A-Za-z0-9 ]+$
You need #"^[A-Za-z0-9 ]+$". The \s character class matches things other than space (such as tab) and you since you want to match sure that no part of the string has other characters you should anchor it with ^ and $.
If you just want alphabets and spaces then you can use: #"[A-Za-z\s]+" to match at least one character or space. You could also use #"[A-Za-z ]+" instead without explicitly denoting the space.
Otherwise please clarify.
In C#, I'd believe it's ^(\w|\s)*$