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()"/>
Related
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"))
This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 7 years ago.
so I'm teaching myself jQuery recently and I just came to the chapter of AJAX. There is an example showing how to check the validation for phone number and I don't know what's going on and how it works. Here is the snippet of code:
// Validate a phone number field
$( "#form" ).submit(function( event ) {
var inputtedPhoneNumber = $( "#phone" ).val();
// Match only numbers
var phoneNumberRegex = /^\d*$/;
// If the phone number doesn't match the regex
if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
// Usually show some kind of error message here
// Prevent the form from submitting
event.preventDefault();
} else {
// Run $.ajax() here
}
});
What I don't understand is this:
var phoneNumberRegex = /^\d*$/;
I did some research for phone number validation and it all has something like this: a pair of "/ /" and some stuff between them and I've never seen this before, anyone can explain what is going on here and why it works? Any help will be appreciated, thank you!
In JavaScript a regular expression can be defined by placing a regular expression pattern between two / slash characters.
In the case of your example the regular expression pattern means:
^ - start matching from the very start of the string sequence;
\d* - match zero or more digit characters 0-9;
$ - keep matching until the very end of the string sequence.
In short, this pattern requires that the entire string sequence is composed of only digit characters and nothing else.
The resulting regular expression object can then call the test function on a string sequence to test whether or not that sequence fits the pattern, and it will only evaluate to true if the string sequence exactly matches the regular expression.
/^\d*$/ simply matches a string that begins with (^) a number, contains an arbitrary amount of digits (\d*) and also ends with a number ($).
http://regexr.com/3ar56 - This will give you an idea of what the regex statement does.
var phoneNumberRegex = /^\d*$/;
the above code sets the variable phoneNumberRegex with a regex statement. The statement does nothing on it's own, but
!phoneNumberRegex.test( inputtedPhoneNumber )
tells it to test the variable inputtedPhoneNumber to see if it is not formatted the way the regex statement suggests it should be. ^\d sees if it starts with a digit * says that it will accept any number of the previous regex property, in this case \d, which tests for a digit. $ states that when the last digit is given it should stop matching. If you put a space after the number it won't match.
so this: ^/d*$
says:
if it starts with a digit collect everything between that first digit and the end of the digit string.
If it the string inside inputtedPhoneNumber doesn't have the specified format it won't match.
This question already has an answer here:
Need to do a right trim on ajax query in javascript?
(1 answer)
Closed 8 years ago.
I wanted to check whether my string which ends with special character or not. If my string contains special character at the end, then need to trim at the right. if not, do nothing.
My piece of code:
var s = 'acbd#';
var x = 'abcd#e'
Expected Result:
acbd
abcd#e
any help on this?
You can use regular expression to replace the special characters with empty string, like this:
s.replace(/[#]+$/, "");
x.replace(/[#]+$/, "");
You can specify more special characters inside of square brackets.
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
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
I have the following javascript code:
function checkLegalYear() {
var val = "02/2010";
if (val != '') {
var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");
if (regEx.test(val)) {
//do something
}
else {
//do something
}
}
}
However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.
Because you're creating your regular expression from a string, you have to double-up your backslashes:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");
When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like
"^(0[1-9]|1[0-2])/\d{4}$"
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
Note that \d is now just d.
By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.
There's really no reason here not to use regular expression syntax instead:
var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;
edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.