JS Regex lookahead - javascript

I want to be able to match these types of strings (comma separated, and no beginning or trailing spaces):
LaunchTool[0].Label,LaunchTool[0].URI,LaunchTool[1].Label,LaunchTool[1].URI,LaunchItg[0].Label,LaunchItg[0].URI,csr_description
The rules, in English, are:
1) Zero or more instances of [] where the brackets must contain only one number 0-9
2) Zero or more instances of ., where . must be followed by a letter
3) Zero or more instances of _, where _ must be followed by a letter
I currently have this regex:
/^([a-z]){1,}(\[[0-9]\]){0,}(\.){0,}[a-z]{1,}$/i
I cannot figure out why
"aaaa" doesn't match
furthemore,
"aaaa[0].a" matches, but "aaaa[0]" does not...
anyone know what's wrong? I believe I might need a lookahead to make sure . and _ characters are followed by a letter? Perhaps I can avoid it.

this regex can match "aaaa", try getting value of
(/^([a-z]){1,}(\[[0-9]\]){0,}(\.){0,}[a-z]{1,}$/i).test("aaaa")
"aaaa[0]" does not match, because there is [a-z]{1,} in the end of expression. once "[0]" is matched by (\[[0-9]\]){0,}, trailing [a-z]{1,} must be shown at the end of string

Use optional capture groups. Example: ([a-z])?.
Here is what i ended up with:
/^((\w+)(\[\d+\])?\.?(\w+)?,?)+$/
Shorthands explanation:
* = {0,}
+ = {1,}
\w = [A-Za-z0-9_]
\d = [0-9]

Related

REgex for non repeating alphabets comma seperated

I have a requirement where I need a regex which
should not repeat alphabet
should only contain alphabet and comma
should not start or end with comma
can contain more than 2 alphabets
example :-
A,B --- correct
A,B,C,D,E,F --- correct
D,D,A --- wrong
,B,C --- wrong
B,C, --- wrong
A,,B,C --- wrong
Can anyone help ?
Another idea with capturing and checking by use of a lookahead:
^(?:([A-Z])(?!.*?\1),?\b)+$
You can test here at regex101 if it meets your requirements.
If you don't want to match single characters, e.g. A, change the + quantifier to {2,}.
The statement of the question is incomplete in several respects. I have made the following assumptions:
Considering that D,D,A is incorrect I assume that a letter cannot be followed by a comma followed by the same letter.
The string may contain the same letter more than once as long as #1 is satisfied.
Considering that A,,B,C is incorrect I assume a comma cannot follow a comma.
Since the examples contain only capital letters I will assume that lower-case letters are not permitted (though one need only set the case-indifferent flag (i) to permit either case).
We observe that the requirements are satisfied if and only if the string begins with a capital letter and is followed by a sequence of comma-capital letter pairs, provided that no capital letter is followed by a comma followed by the same letter. We therefore can attempt to match the following regular expression.
^(?:([A-Z]),(?!\1))*[A-Z]$
Demo
The elements of the expression are as follows.
^ # match beginning of string
(?: # begin a non-capture group
([A-Z]) # match a capital letter and save to capture group 1
, # match a comma
(?!\1) # use negative lookahead to assert next character is not equal
# to the content of capture group 1
)* # end non-capture group and execute it zero or more times
[A-Z] # match a capital letter
$ # match end of string
Here is a big ugly regex solution:
var inputs = ['A,B', 'D,D,D', ',B,C', 'B,C,', 'A,,B'];
for (var i=0; i < inputs.length; ++i) {
if (/^(?!.*?([^,]+).*,\1(?:,|$))[^,]+(?:,[^,]+)*$/.test(inputs[i])) {
console.log(inputs[i] + " => VALID");
}
else {
console.log(inputs[i] + " => INVALID");
}
}
The regex has two parts to it. It uses a negative lookahead to assert that no two CSV entries ever repeat in the input. Then, it uses a straightforward pattern to match any proper CSV delimited input. Here is an explanation:
^ from the start of the input
(?!.*?([^,]+).*,\1(?:,|$)) assert that no CSV element ever repeats
[^,]+ then match a CSV element
(?:,[^,]+)* followed by comma and another element, 0 or more times
$ end of the input
This one could suit your needs:
^(?!,)(?!.*,,)(?!.*(\b[A-Z]+\b).*\1)[A-Z,]+(?<!,)$
^: the start of the string
(?!,): should not be directly followed by a comma
(?!.*,,): should not be followed by two commas
(?!.*(\b[A-Z]+\b).*\1): should not be followed by a value found twice
[A-Z,]+: should contain letters and commas only
$: the end of the string
(?<!,): should not be directly preceded by a comma
See https://regex101.com/r/1kGVSB/1

Regular expression to validate a string starts with a char and contains allowed chars

I need help with my regular expression written in javascript.
I have tried using the regularExpression generator online, and the best i can come up with is the this:
^[a-z.-]{0,50}$
The expression must validate the following
String first char MUST start with a-z (no alpha)
String can contain any char in range a-z (no alpha), 0-9 and the characters dash "-" and dot "."
String can be of max length 50 chars
Examples of success strings
username1
username.lastname
username-anotherstring1
this.is.also.ok
No good strings
1badusername
.verbad
-bad
also very bad has spaces
// Thanks
Almost (assuming "no alpha" means no uppercase letters)
https://regex101.com/r/O9hvLP/3
^[a-z]{1}[a-z0-9\.-]{0,49}$
The {1} is optional, I put it there for descriptive reasons
I think this should cover what you want
^[a-z][a-z0-9.-]{0,49}$
That is starts a-z but then has 0-49 of a-z, 0-9 or .-
Live example: https://regexr.com/5k8eu
Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add A-Z as well!
If the . and - can not be at the end, and there can not be consecutive ones, another option could be:
^[a-z](?=[a-z0-9.-]{0,49}$)[a-z0-9]*(?:[.-][a-z0-9]+)*$
Explanation
^ Start of string
[a-z] Match a single char a-z
(?=[a-z0-9.-]{0,49}$) Assert 0-49 chars to the right to the end of string
[a-z0-9]* Match optional chars a-z0-9
(?:[.-][a-z0-9]+)* Optionally match either . or - and 1+ times a char a-z0-9
$ End of string
Regex demo

Regex - match variable beginned with $ in javascript?

I want to match all the variables like $bar, $foo, I only have this until the moment:
(\$)+[A-Za-z]
Just this:
/\$[\w_]+/g
And if you want to check the variable does not start with number, just check by negative lookahead. (?![\d])
/\$(?![\d])[\w_]+/g
/g to match all.
This should match some common valid variables which consists of [A-Za-z0-9_] but don't start with number.
/(\$(?!\d)\w+)/g
/ .. /g // regular expression is put between two //, the g behind is flag for global
( .. ) // a capturing group, can be called using \1 or $1 depending on regex processor
\$ // escaped character `$`
(?!\d) // negative lookahead - ensures that next character after $ isn't a match ->
-> \d // matches one digit
\w+ // one or more "word characters". Matches the ASCII characters [A-Za-z0-9_]
note: if you are going to match all variable names globally, you don't need any capturing groups, so just use /\$(?!\d)\w+/g.
According to php.net, this is the right regexp: \$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
EDIT: I have just noticed you are not matching PHP variables at all, but you get the idea now. :)
For fun http://regex.alf.nu/
\$[A-Za-z]+\w*
Explained: $ in the start, one or more letters, followed by 0 or more valid variable letters (depending on language).
See https://www.regex101.com/r/cB1bM1/1 for a detailed explanation.
The regex you may need is:
\$\w+

Query on Javascript RegEx

I need a regex that allows 0-9, a-z, A-Z, hyphen, question mark and "/" slash characters alone. Also the length should be between 5 to 15 only.
I tried as follows, but it does not work:
var reg3 = /^([a-zA-Z0-9?-]){4,15}+$/;
alert(reg3.test("abcd-"));
length should be between 5 to 15 only
Is that why you have this?
{4,15}+
Just use {5,15}; it’s already a quantifier, and a + after it won’t work. Apart from that, the group isn’t necessary, but things should work.
/^[a-zA-Z0-9?/-]{5,15}$/
(I also added a slash character.)
This is what you need:
if (/^([a-z\/?-]{4,15})$/i.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
REGEX EXPLANATION
^([a-z\/?-]{4,15})$
Options: Case insensitive
Assert position at the beginning of the string «^»
Match the regex below and capture its match into backreference number 1 «([a-z\/?-]{4,15})»
Match a single character present in the list below «[a-z\/?-]{4,15}»
Between 4 and 15 times, as many times as possible, giving back as needed (greedy) «{4,15}»
A character in the range between “a” and “z” (case insensitive) «a-z»
The literal character “/” «\/»
The literal character “?” «?»
The literal character “-” «-»
Assert position at the very end of the string «$»
Couple issues,
you need {5,15} instead of {4,15}+
need to include /
Your code can be rewritten as
var reg3 = new RegExp('^[a-z0-9?/-]{5,15}$', 'i'); // i flag to eliminate need of A-Z
alert(reg3.test("a1?-A7="));
Update
Let's not confuse can be with MUST be and concentrate on the actual thing I was trying to convey.
{4,15}+ part in /^([a-zA-Z0-9?-]){4,15}+$/ should be written as {5,15}, and / must be included; which will make your regexp
/^([a-zA-Z0-9?/-]){5,15}$/
which CAN be written as
/^[a-z0-9?/-]{5,15}$/i // i flag to eliminate need of A-Z
Also I hope everybody is OK with use of /i

Regular Expression for alphabets, numbers and symbols

I am looking for a regex for allowing
Alphabets case insensitive [a-zA-Z]
hyphen and underscore [-_]
forward and backward slashes [/\\\\]
numbers [0-9]
Hence
var regex = new RegExp('^[a-zA-Z-_][/\\\\]*$');
regex.test('ABC/90-1_AB');
does not work.
Your current regexp (/^[a-zA-Z-_][/\\\\]*$/) is looking for a string that start with a letter, - or _ who are then followed by 0 or more / or \ that end the string.
Put it inside 1 bracket :
'^[-_/0-9a-zA-Z\\\\]*$'
Try:
var regex = new RegExp('[\w\\/-]','i'); // \w matches alphanumeric characters and underscore
regex.test('ABC/90-1_AB'); // returns true
JSFIDDLE
Since you aren't willing to have complex RegExp why making it difficult, when you can just match your needs with explicitly required symbols

Categories

Resources