Why does this regex not exclude hyphens or brackets? [duplicate] - javascript

This question already has answers here:
Why this javascript regex doesn't work?
(1 answer)
Match exact string
(3 answers)
Closed 5 years ago.
Regex is the bane of my existence. I've done plenty tutorials, but the rules never stick, and when I look them up they seem to conflict. Anyways enough of my whining. Could someone tell me why this regex doesn't exclude hyphens or brackets:
/^[A-Za-z_][A-Za-z\d_]*/
The way I understand it (or at least what I'm trying to do), the ^ character dictates that the regex should start with the next thing on the list That means the regex should start with [A-Za-z_] or any character a-z and A-Z as well as and underscore _. Then the string can have anything that includes [A-Za-z\d_] which is any alphanumeric character and an underscore. Then I use the * to say that the string can have any number of what was presented previously (any alphanumeric character plus underscore). At no point to I specify a bracket [ or a hyphen -. Why does this expression not exclude these characters
Extra info
I'm verifying this with javascript:
function variableName(name) {
const reg = RegExp("^[A-Za-z_][A-Za-z\d_]*")
return reg.test(name)
}
function variableName("va[riable0") // returns true should be false

It's actually matching the first 2 letters("va"), that's why it's true.
To match the whole phrase, your reg expression should have "$" at the end:
"^[A-Za-z_][A-Za-z\d_]*$"

Your regex matches the part of the string that does not contain the bracket, because your're missing the $ anchor that would (together with ^) force it to match the whole string. Use
const reg = /^[A-Za-z_][A-Za-z\d_]*$/g
// ^
function variableName(name) {
return reg.test(name)
}
console.log(variableName("va[riable0"))

Related

Regex to not match a pattern in Javascript [duplicate]

This question already has answers here:
Regex: match everything but a specific pattern
(6 answers)
Closed 7 months ago.
I need a reqular expression to not match this (/^[a-zA-Z][a-zA-Z0-9]+$/) pattern, where the string needs to start with alphabet followed by number and alphabet, with no special characters.
I tried with (/^?![a-zA-Z]?![a-zA-Z0-9]+$/) and not able to get appropriate answer.
Example:
P123454(Invalid)
PP1234(Invalid)
1245P(valid)
##$124(valid)
Thanks in advance.
^ means start with, So it should start with an alphabetic letter, then any number \d of alphabetic letters a-z with i case insensitive flag.
const check = (str) => {
return /^[^a-z].*/i.test(str)
}
console.log(check('P123454'))
console.log(check('PP1234'))
console.log(check('1245P'))
console.log(check('##$124'))
This regex might be helpful:
/^[^a-zA-Z]+.*$/g
Your every valid input (from the question) should be a match.
Regex 101 Demo
Explanation:
Does not allow string starting with a-zA-Z
Everything after than is allowed (I'm not sure if this is a requirement)

Non-greed regex misunderstanding, /\/.*?$/ act like greed [duplicate]

This question already has answers here:
Regex lazy vs greedy confusion
(2 answers)
Why does a simple .*? non-greedy regex greedily include additional characters before a match?
(3 answers)
Closed 3 years ago.
I'm trying this in javascript
/\/.*?$/.exec('foo/bar/tar')[0]
I was expecting to get /tar as result but getting /bar/tar. As far as I understand non-greed regex would take the smallest match.
I'm circumventing this with myvar.split('/').reverse()[0] but I couldn't understand what is going wrong with the regex.
There is nothing wrong with the regex but the pattern \/.*?$ matches from the first forward slash until the end of the string non greedy.
The dot matches any character except a newline and does not take a forward slash into account, so that will result in /bar/tar.
If you want to match /tar, you could match a forward slash, followed by not matching anymore forward slashes using a negated character class and then assert the end of the string.
\/[^\/]+$
Pattern demo
console.log(/\/[^\/]+$/.exec('foo/bar/tar')[0]);

Javascript regular expression to validate whether both () brackets are present [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
Techies,
I'm working on kind of calculator, am not much comfortable with regex. My need is JavaScript regular expression to validate whether both ( ) brackets are present, there may be some character inside the brackets.
suggestions please
Simple regex:
var string = '1234 + 1234 (5)';
if (string.match('\(|\)')) {
console.log('() found')
}
Simply matching
\(.*\)
will match if both an opening, and a closing parentheses are present. (Parentheses need to be escaped since it's a special character in regex.) .* matches anything, including an empty string.
But I assume you'd want to allow strings without any parentheses as well. This regex allows for any number of pairs of parentheses (not nested) or none at all:
^[^()]*(?:\([^()]*\)[^()]*)*$
It matches start of string ^, a string of any length not containing parentheses [^()]*. Then any number of the combination 1. Opening P(arentheses) 2. Any length string w/o P's. 3. A closing P. 4. Any length string w/o P's. (Possibly repeated any number of times.) Finally it matches end of string $.
Working example (Type an expression into the input control, and press Enter.):
var inputExpression = document.getElementById("expression");
function testExpression(){
console.log(inputExpression.value.match(/^[^()]*(?:\([^()]*\)[^()]*)*$/) ? "Well formed" : "Unbalanced parentheses");
// inputExpression.value = '';
}
inputExpression.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
testExpression();
}
});
Enter an expression:<input id="expression" type="text" onBlur="testExpression()"/>

regex remove white space after text [duplicate]

This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 4 years ago.
From this regex,
text.replace(/^\s+|\s+$/g,"").replace(/ +/g,' ')
how do I remove the regex just for trailing white space?
I am new to regex and did some research but I'm not able to understand the pattern.
/^\s+|\s+$/g means
^ // match the beginning of the string
\s+ // match one or more whitespace characters
| // OR if the previous expression does not match (i.e. alternation)
\s+ // match one or more whitespace characters
$ // match the end of the string
The g modifier indicates to repeat the matching until no match is found anymore.
So if you want to remove the part the matches whitespace characters at the end of the string, remove the |\s+$ part (and the g flag since ^\s+ can only match at one position anyway - at the beginning of the string).
Useful resources to learn regular expressions:
http://www.regular-expressions.info/
Regex in JavaScript (since this seems to be JavaScript).

JavaScript: \\d{4} RegExp allows more than 4 digits [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
Have following validation for year value from text input:
if (!year.match(new RegExp('\\d{4}'))){
...
}
RegExp equals null if numeric of digits from 0 to 3. It's OK.
In case 4 digits it returns value.It's OK.
In case more than 4 digits it returns value again,that it's NOT OK.
Documentation says {n} declaration means exact number,but works like:
exact+
With such ugly validation it work's fine:
if (!year.match(new RegExp('\\d{4}')) || year.length>4){
...
}
I wish to utilize RegExp object only.
Yes it would allow more than 4 digits since it would be a partial match use the ^ and $ to mark the beginning and the end of the string.
if (!year.match(new RegExp('^\\d{4}$'))){
...
}
If you include ^ in your regex it matches the beginning of the string, while $ matches the end, so all up:
^\d{4}$
Will match only against beginning-of-string plus four digits plus end-of-string.
Note that regex literal syntax is generally a bit simpler than saying new Regex():
/^\d{4}$/
// is the equivalent of
new RegExp('^\\d{4}$')
Note that in the literal syntax you don't have to escape backslashes like with the string you pass to the new RegExp(). The forward slashes are not part of the expression itself, you can think of them like quotation marks for regexes.
Also, if you just want to check if a string matches a pattern (yes or no) without extracting what actually matched you should use the .test() method as follows:
if (!/^\d{4}$/.test(year)) {
...
}
It's matching the first four digits and then the fact that there's any remaining digits it neither here nor there. You need to change your regex so it stops after these four digits, say, by using the string termination anchors:
^\d{4}$
Try instead:
'^\\d{4}$'
What you had will match anything with 4 digits anywhere, such as asd1234asd or 123456789

Categories

Resources