Regex to match card code input - javascript

How can I write a regex to match strings following these rules?
1 letter followed by 4 letters or numbers, then
5 letters or numbers, then
3 letters or numbers followed by a number and one of the following signs: ! & # ?
I need to allow input as a 15-character string or as 3 groups of 5 chars separated by one space.
I'm implementing this in JavaScript.

I'm not going to write out the whole regex for you since this is homework, but here are some hints which should help you out:
Use character classes. [A-Z] matches all uppercase. [a-z] matches all lowercase. [0-9] matches numbers. You can combine them like so [A-Za-z0-9].
Use quantifiers like {n} so [A-Z]{3} gives you 3 uppercase letters.
You can put other characters in character classes. Let's say you wanted to match % or # or #, you could do [%##] which would match any of those characters.
Some meta-characters (characters which have special meaning in the context of regular expressions) will need to be escaped like so: \$ (since $ matches the end of a line)
^ and $ match the beginning and end of the line respectively.
\s matches white-space, but if you sanitize your input, you shouldn't need to use this.
Flags after the regex do special things. For example in /[a-z]/i, the i ignores case.

This should be it:
/^[a-z][a-z0-9]{4} ?[a-z0-9]{5} ?[a-z0-9]{3}[0-9][!&#?]$/i
Feel free to change 0-9 and [0-9] with \d if you see fit.
The regex is simple and readable enough. ^ and $ make sure this is a whole match, so there aren't extra characters before or after the code, and the /i flag allows upper or lower case letters.

I would start with a tutorial.
Pay attention to the quantifiers (like {N}) and character classes (like [a-zA-Z])

^[a-zA-Z][a-zA-Z0-9]{4} ?[a-zA-Z0-9]{5} ?[a-zA-Z0-9]{3}[\!\&\#\?]$

Related

RegEx for single asterisk (*) and alphanumeric

I need a javascript regex that accepts any alphanumeric character (can be any amount of characters or 0 characters if an asterisk is present) and a single asterisk anywhere in the string (but it does not need the asterisk).
Matches
*
abc
*abc
abc*
a*bc
Invalid Matches
**
*_abc
*abc*
abc**
**abc
I have
^([A-Za-z\d*]?)+$
but that matches multiple asterisks and I'm not sure how to only allow one https://regex101.com/r/a1C9bf/1
You may use this regex with a negative lookahead:
/^(?!(?:.*\*){2})[A-Za-z\d*]+$/gm
Updated RegEx Demo
Negative lookahead (?!(?:.*\*){2}) fails the match if there are more than one * in input.
Without requiring any look-ahead, you could use ^([\da-zA-Z]+|[\da-zA-Z]*\*[\da-zA-Z]*)$
https://regex101.com/r/xW2IvR/2
You could do:
^(?=.)[A-Za-z\d]*\*?[A-Za-z\d]*$
This will match any string that that's at least one character long ((?=.)), starts with zero or more alphanumeric characters, contains an optional *, and ends with zero or more alphanumeric characters.
You could also replace [A-Za-z\d] with [^\W_] to make it a little shorter (but slightly harder to read):
^(?=.)[^\W_]*\*?[^\W_]*$
You want one match one of two possible cases:
an asterisk surrounded by zero or more alphanumeric characters
one or more alphanumeric characters
Then this is your regex:
^([a-zA-Z\d]*\*[a-zA-Z\d]*|[a-zA-Z\d]+)$

Regex for a string which do not start with a number and allow only alphanumeric

I am trying to create a javascript regex for below conditions
Allow Alphanumeric only
But also allow underscore(_)
Don't allow to start with a number
Don't allow to start with an underscore
I have created a regex ^(?![0-9]|[_].*$).* which will work for last two conditions above. Please suggest how can I add an and condition to make it work for all above scenarios.
You may use the following regex:
^[A-Za-z]\w*$
Details
^ - start of string
[A-Za-z] - any ASCII letter
\w* - zero or more letters/digits/_
$ - end of string.
To allow an empty string match, wrap the whole pattern with an optional non-capturing group:
^(?:[A-Za-z]\w*)?$
^^^ ^^
You can use this regex:
^(?![0-9_])\w+$
RegEx Demo
(?![0-9_]) is negative lookahead to fail the match when we have a digit or _ at the start.
you can use the regex
^[a-zA-Z][A-Za-z0-9_]*$
see the regex101 demo
You may be thinking too literally about the last two requirements. If it's alphanumeric (so.. a-z and 0-9, right?) then saying "dont allow numbers or underscore at the start" is probably the same as "must start with a letter"
^[a-z][a-z0-9_]*$
This is "must start with a-z", followed by "must follow with zero or more letters, numbers or underscores. The ^ outside of a character class (for example [a-z] is a character class) means "start of input". The $ means end of input.
If you interpreted the last two requirements literally, you could write:
[^0-9_]
This means "any character that is not 0-9 and also not an underscore" but it doesn't necessarily restrict the user from entering something other than a-z as the first character, so they might enter a #, and it would pass..

Regex for a valid hashtag

I need regular expression for validating a hashtag. Each hashtag should starts with hashtag("#").
Valid inputs:
1. #hashtag_abc
2. #simpleHashtag
3. #hashtag123
Invalid inputs:
1. #hashtag#
2. #hashtag#hashtag
I have been trying with this regex /#[a-zA-z0-9]/ but it is accepting invalid inputs also.
Any suggestions for how to do it?
The current accepted answer fails in a few places:
It accepts hashtags that have no letters in them (i.e. "#11111", "#___" both pass).
It will exclude hashtags that are separated by spaces ("hey there #friend" fails to match "#friend").
It doesn't allow you to place a min/max length on the hashtag.
It doesn't offer a lot of flexibility if you decide to add other symbols/characters to your valid input list.
Try the following regex:
/(^|\B)#(?![0-9_]+\b)([a-zA-Z0-9_]{1,30})(\b|\r)/g
It'll close up the above edge cases, and furthermore:
You can change {1,30} to your desired min/max
You can add other symbols to the [0-9_] and [a-zA-Z0-9_] blocks if you wish to later
Here's a link to the demo.
To answer the current question...
There are 2 issues:
[A-z] allows more than just letter chars ([, , ], ^, _, ` )
There is no quantifier after the character class and it only matches 1 char
Since you are validating the whole string, you also need anchors (^ and $)to ensure a full string match:
/^#\w+$/
See the regex demo.
If you want to extract specific valid hashtags from longer texts...
This is a bonus section as a lot of people seek to extract (not validate) hashtags, so here are a couple of solutions for you. Just mind that \w in JavaScript (and a lot of other regex libraries) equal to [a-zA-Z0-9_]:
#\w{1,30}\b - a # char followed with one to thirty word chars followed with a word boundary
\B#\w{1,30}\b - a # char that is either at the start of string or right after a non-word char, then one to thirty word (i.e. letter, digit, or underscore) chars followed with one to thirty word chars followed with a word boundary
\B#(?![\d_]+\b)(\w{1,30})\b - # that is either at the start of string or right after a non-word char, then one to thirty word (i.e. letter, digit, or underscore) chars (that cannot be just digits/underscores) followed with a word boundary
And last but not least, here is a Twitter hashtag regex from https://github.com/twitter/twitter-text/tree/master/js... Sorry, too long to paste in the SO post, here it is: https://gist.github.com/stribizhev/715ee1ee2dc1439ffd464d81d22f80d1.
You could try the this : /#[a-zA-Z0-9_]+/
This will only include letters, numbers & underscores.
A regex code that matches any hashtag.
In this approach any character is accepted in hashtags except main signs !##$%^&*()
(?<=(\s|^))#[^\s\!\#\#\$\%\^\&\*\(\)]+(?=(\s|$))
Usage Notes
Turn on "g" and "m" flags when using!
It is tested for Java and JavaScript languages via https://regex101.com and VSCode tools.
It is available on this repo.
Unicode general categories can help with that task:
/^#[\p{L}\p{Nd}_]+$/gu
I use \p{L} and \p{Nd} unicode categories to match any letter or decimal digit number. You can add any necessary category for your regex. The complete list of categories can be found here: https://unicode.org/reports/tr18/#General_Category_Property
Regex live demo:
https://regexr.com/5tvmo
useful and tested regex for detecting hashtags in the text
/(^|\s)(#[a-zA-Z\d_]+)/ig
examples of valid matching hashtag:
#abc
#ab_c
#ABC
#aBC
/\B(?:#|#)((?![\p{N}_]+(?:$|\b|\s))(?:[\p{L}\p{M}\p{N}_]{1,60}))/ug
allow any language characters or characters with numbers or _.
numbers alone or numbers with _ are not allowed.
It's unicode regex, so if you are using Python, you may need to install regex.
to test it https://regex101.com/r/NLHUQh/1

Find single backslashes followed by alphabet

I need to a regres that find all single backslashes followed by an alphabet.
So I want to find backslashes that exist in patterns like these:
\a
\f
\test
and not in these patterns:
\\a
\"
Thanks
Updated:
As #Amadan points out in the comments below, JavaScript does not implement lookbehind, which basically breaks my original answer.
There is an approach suggested in this stackoverflow post that may be a reasonable path to take for this problem.
Basically the poster suggests reversing the string and using lookahead to match. If we were to do that, then we would want to match a string of alphabetic characters followed by a single backslash, but not followed by multiple backslashes. The regex for that would look like this:
/[a-zA-Z]+\\(?![\\]+)/g
[a-zA-Z]+ - match one or more alphabetic characters
\\ - followed by a single backslash
(?![\\]+) - not followed by one or more backslashes
g - match it globally (more than one occurrence)
The downside of this approach (aside from having to reverse your string) is that you can't match only the backslash, but will have to also match the alphabetic characters that come before it (since JS doesn't have lookbehind).
Original Answer (using lookbehind):
/(?<!\\)\\[a-zA-Z]+/g (using negative lookbehind) will match a single backslash followed by one or more letters of the alphabet, regardless of case. This regular expression breaks down as follows:
(?<!\\)\\ - use negative lookbehind to match a \ that is not preceded by a \
[a-zA-Z]+ - match one or more letters of the alphabet, regardless of case
g - match it globally
If you only want to match the \ and not the alphabetic characters, then you can use positive lookahead. The regex for that would look like: /(?!>\\)\\(?=[a-zA-Z]+)/g and would break down like this:
(?<!\\)\\ - use negative lookbehind to match a \ that is not preceded by a \
(?=[a-zA-Z]+) - and is followed by one or more alphabetic characters
g - match it globally
If you only want the regex to match backslashes at the beginning of a line, prepend a ^ to it.
You can use a tool like Rubular to test and play with regular expressions.

Regex - how to ignore order of the matched groups? [duplicate]

This question already has answers here:
Password REGEX with min 6 chars, at least one letter and one number and may contain special characters
(10 answers)
Closed 2 years ago.
I'm trying to create a regex validation for a password which is meant to be:
6+ characters long
Has at least one a-z
Has at least one A-Z
Has at leat one 0-9
So, in other words, the match will have :
at least one a-z, A-Z, 0-9
at least 3 any other characters
I've came up with:
((.*){3,}[a-z]{1,}[A-Z]{1,}[0-9]{1,})
it seems pretty simple and logical to me, but 2 things go wrong:
quantifier {3,} for (.*) somehow doesn't work and destroys whole regex. At first I had {6,} at the end but then regex would affect the quantifiers in inner groups, so it will require [A-Z]{6,} instead of [A-Z]{1,}
when I remove {3,} the regex works, but will match only if the groups are in order - so that it will match aaBB11, but not BBaa11
This is a use case where I wouldn't use a single regular expression, but multiple simpler ones.
Still, to answer your question: If you only want to validate that the password matches those criteria, you could use lookaheads:
^(?=.{6})(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])
You're basically looking for a position from which you look at
6 characters (and maybe more to follow, doesn't matter): (?=.{6})
maybe something, then a lowercase letter: (?=.*?[a-z])
maybe something, then an uppercase letter: (?=.*?[A-Z])
maybe something, then a digit: (?=.*?[0-9])
The order of appearance is arbitrary due to the maybe something parts.
(Note that I've interpreted 6 characters long as at least 6 characters long.)
I believe this is what you want:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[!-~]{6,}$
If we follow your spec to the letter, your validation password looks like this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,}$
However, we need to improve on this, because apart from the number, lower-case and upper-case letter, are you really willing to accept any character? For instance, can the user use a character in the Thai language? A space character? A tab? Didn't think so. :)
If you want to allow all the printable ASCII characters apart from space, instead of a dot, we can use this character range: [!-~]
How does it work?
The ^ anchor makes sure we start the match at the start of the string
The (?=.*[a-z]) lookahead ensures we have a lower-case character
The (?=.*[A-Z]) lookahead ensures we have an upper-case character
The (?=.*[0-9]) lookahead ensures we a digit
The (?=.*[a-z]) lookahead ensures we have a lower-case character
The [!-~]{6,} matches six or more ASCII printable ASCII characters that are not space.
The $ ensures we have reached the end of the string (otherwise, the password could contain more characters that are not allowed).
you could use this pattern ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,}

Categories

Resources