I've asked a couple of JavaScript regular expression questions over the last few days as I try to piece together a larger regular expression but I am still having some trouble so I am going to ask about the entire problem, which is probably what I should have done in the first place.
Essentially, what I need is a regular expression that will match all of the following:
An empty string.
A string that contains at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
So some examples are as follows:
"" = true
"+" = false
"+abc" = true
"abc" = true
"+1" = false
"+12" = true
"+2" = true
Based on your stated requirements as amended, you want to match only:
An empty string, ^$
A string that contains at least one alpha-numeric character but does not start with a +1, ^(?!\+1).*[a-zA-Z0-9]
A string that starts with +1 and has at least 1 more alpha-numeric character, ^\+1.*[a-zA-Z0-9]
Put together, that is:
^$|^(?!\+1).*[a-zA-Z0-9]|^\+1.*[a-zA-Z0-9]
Or, if you like:
^($|(?!\+1).*[a-zA-Z0-9]|\+1.*[a-zA-Z0-9])
^(?:\+1[a-zA-Z0-9]+|(?!\+1).*[a-zA-Z0-9]+.*)?$
Explanation:
The regex is separated in two cases: ( CASE1 | CASE2 )
First case: \+1[a-zA-Z0-9]+ matches every text that starts with +1 and is followed by one or more alphanumeric char ([a-zA-Z0-9]+ stands for pick one or more chars that are either from a to z, from A to Z or from 0 to 9)
Second case: (?!\+1).*[a-zA-Z0-9]+.* matches every text that does NOT start with +1 ((?!\+1)), and is followed by as many characters you want as long as it contains at least one alphanumeric char (.*[a-zA-Z0-9]+.* stands for pick 0 or more of whatever char you want, plus the regex explained above, plus 0 or more of whatever char again)
These two cases respectively match your rules #3 and #2.
The rule #1 is taken care of by the ? at the end of the whole expression, meaning all of that is optional, therefore it can also be an empty string.
Please note some things such as:
(?:something) is used to match a string, but not capture it.
(?!something) is used to make sure it doesnt match a string
\ is used to escape special characters like + when you want them to stand as regular characters
+ is used to say one or more of the preceding item
* is used to say zero or more of the preceding item
Hope i helped!
Based on your most updated requirements:
An empty string.
A string that contains at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
Here is what I'd use:
/^([]|(\+1)?.*[a-zA-Z0-9]+.*)$/
In plan english, that regex says to look for a string that is:
Empty, or
Has an alphanumberic character (and optionally starts with +1 as well)
A string that contains at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
Let's rephrase this a little bit :
A string that has at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
Try again :
but does not start with a +1 | A string that has at least one alpha-numeric character A string that starts with +1 | and has at least 1 more alpha-numeric character.
So what does this let us too?
Nothing. You just wanna match an empty string. I mean really ?
//var re = /(^$)/; //Matches empty
//var re = /(^[a-z0-9]+)/; //matches only string no plus
//var re = /(^\+([0a-z2-9])([a-z0-9].*)?)/; //Matches the + [not one] requirement
//Joined together with | for or
//Might be simplified more, but this works ;)
var re = /(^([a-z0-9]+.*|[a-z0-9]+.*|\+1[a-z0-9]+.*|\+([0a-z2-9])([a-z0-9].*)?)?$)/i;
function testIt( str, expected ) {
if( !!re.exec( str ) === expected ) {
console.info(str + "\tpassed" );
} else{
console.error(str + "\tfailed" );
}
}
testIt("", true);
testIt("+", false);
testIt("+abc", true);
testIt("abc", true);
testIt("+1", false);
testIt("+12", true);
testIt("+12_", true);
testIt("+2", true);
testIt("+2c", true);
testIt("+2_", false);
testIt("+007", true);
JSFiddle
Related
I'm trying to limit an input field to only numbers and the possibility of a "+" sign just at the string's [0] index. The idea is to let the user type their phone number, I have come up with this:
function main() {
let phone = document.getElementById('phone');
let phoneRegex = /[a-zA-Z]|[-!$%^&*()_|~=`{}[\]:";'<>?,./]/;
phone.value = phone.value.replace(phoneRegex, '');
console.log(phone.value);
}
<input id="phone">
<button onclick="main()">Run</button>
The thing is, this works fine, but I want to limit the first character to only a digit or a "+" sign, characters coming from index [1] and on should only be numbers.
I can't come up with an idea on how to solve this
Try this as a starting point (you'll probably want to expand it further to account for total string length, delimiters like -, etc.):
let phoneRegex = /\+?\d+/;
+ in a regular expression has a special meaning, so when we want to match the literal character "+" then we need to escape it. And following it with the ? character makes it optional:
\+?
Next, \d followed by + will match any sequence of one or more digits:
\d+
You can see a visualization of this pattern here.
I want to limit the first character to only a digit or a "+"
sign, characters coming from index [1] and on should only
be numbers.
The regex:
/^\+?\d+$/
means:
From the beginning, one or zero + signs, then one or more numbers until the end.
Note the following regex symbols:
* - zero or more
+ - one or more
? - zero or one
I know I'm late in this game, but adding one more solution for me and other's future references.
I came up with this solution which works for me:
/^(\+|[0-9])?[0-9]{12}$/
Thanks
I have a text input and I require that it only accepts digits (0-9) and blank spaces (" ").
The current regexp to validate this input is:
/((\d{1,})(\s{1,})?){1,}/
Which stands for: one or more groups base on a first group of one or more digits and an optional second group of one or more blank spaces
That will only let me introduce values as: 999999 (only digits) or " " (only blank spaces) or 91 08 8510 903 (mix of digits and spaces).
But actually, I also can insert aaa or other characters.
Dissection
Your regular expression doesn't accept only letters :
/((\d{1,})(\s{1,})?){1,}/.test('aaa') // false
Actually, any character is accepted if the input contains at least one digit :
/((\d{1,})(\s{1,})?){1,}/.test('a1a') // true
That being said, let's skim the fat from your pattern :
"{1,}" equals "+" -> ((\d+)(\s+)?)+
"(.+)?" equals ".*" -> ((\d+)\s*)+
useless brackets -> (\d+\s*)+
This result can be translated to : "one or more digits (\d+) followed by zero or more blank spaces (\s*), one or more times (()+), anywhere in the input". Alternatively, we could say : "at least one digit, anywhere in the input".
What you need is to replace "anywhere in the input" with "from the beginning to the end of the input". This is allowed by the following special characters : ^ (beginning of input) and $ (end of input). Let's make a bunch of tests to see how they work :
requirement regex input .test()
---------------------------------------------------------------------
must contain at least one digit /\d+/ 'a1a' true
must start with at least one digit /^\d+/ '1a' true
must start with at least one digit /^\d+/ 'a1' false
must end with at least one digit /\d+$/ '1a' false
must end with at least one digit /\d+$/ 'a1' true
only digits from the beginning to the end /^\d+$/ '1a1' false
Suggestion
Only digits potentially separated by one whitespace : /^\d+( \d+)*$/.
^ beginning of the input
\d+ a digit, one or more times
( \d+)* a whitespace + same as above, zero or more times
$ end of the input
Usage example :
var r = /^\d+( \d+)*$/;
var isValid = r.test(' 1 '); // false
var isValid = r.test('1 1'); // true
var isValid = r.test('1 1'); // false
More about regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.
try this one
$pattern = '/^[0-9 ]+$/';
if ( preg_match ($pattern, $text) )
{
echo 'allowed';
}
Try this regular expression
/(\d+\s*\d*)+$/
Visualize the results here http://regex101.com/r/dE5uR8
I have tested it online using
http://regexpal.com/
The above regular expression will not accept empty blank spaces at the start. You need atleast one digit. If you want to match the empty spaces at the start also change it to (\d*\s*\d*)+$ which will accept empty spaces also
I need a regular expression to validate a form, based on the value of a drop down. The value, however, is randomly generated by PHP (but is always a 2 digit number).
It needs to be valid for "38|One Evening" The number 38 is what's going to change. So far, I have
//return value of dropdown
var priceOption = $("#price_option-4").val();
//make sure it ends with "One Evening"
var oneEvening = priceOption.match(/^ * + 'One Evening' $/);
Which I thought would match any string as long as it's followed by "one evening"
strings are not to be use with regex, you should just write what you want to match\test inside the regex literal, without the quotes.
/^\d{2}\|One Evening$/.test(priceOption);
// ^^^^^^ Begins with two digits
// ^^ Escaped the | meta char.
// ^^^^^^^^^^^^ Then until the end: One Evening
Simply use
/^\d\d\|One Evening$/.test(priceOption);
For xx|One Evening
/^\d{2}\|One Evening$/
/^.+?One Evening$/
Breaking it down
// ^ starts with
// . any character
// + quantifier - one or more of preceding character
// ? non-greedy - ensure regex stops at One Evening.
// One Evening = literal text
// $ match end of string.
Note that my answer reflects the requirement to match any sequence of characters, then One Evening.
I think you may be better off being more specific and ensuring you definitely have two numeric characters.
If you can it is best to be specific. Try the following:
// <start of string> <2 digits> <|One Evening> <end of string>
/^\d{2}\|One Evening$/.test( priceOption );
I need to check whether information entered are 3 character long, first one should be 0-9 second A-Z and third 0-9 again.
I have written pattern as below:
var pattern = `'^[A-Z]+[0-9]+[A-Z]$'`;
var valid = str.match(pattern);
I got confused with usage of regex for selecting, matching and replacing.
In this case, does[A-Z] check only one character or whole string ?
Does + separate(split?) out characters?
1) + matches one or more. You want exactly one
2) declare your pattern as a REGEX literal, inside forward slashes
With these two points in mind, your pattern should be
/^[A-Z][0-9][A-Z]$/
Note also you can make the pattern slightly shorter by replacing [0-9] with the \d shortcut (matches any numerical character).
3) Optionally, add the case-insensitive i flag after the final trailing slash if you want to allow either case.
4) If you want to merely test a string matches a pattern, rather than retrieve a match from it, use test(), not match() - it's more efficient.
var valid = pattern.test(str); //true or false
+ means one or more characters so a possible String would be ABCD1234EF or A3B, invalid is 3B or A 6B
This is the regex you need :
^[0-9][A-Z][0-9]$
In this case, does[A-Z] check only one character or whole string ?
It's just check 1 char but a char can be many times in a string..
you should add ^ and $ in order to match the whole string like I did.
Does + separate(split?) out characters?
no.
+ sign just shows that a chars can repeat 1+ times.
"+" means one or more. In your case you should use exact quantity match:
/^\w{1}\d{1}\w{1}$/
OK Regex is one of the most confusing things to me. I'm trying to do this in Javascript. I have a search field that the user will enter a series of characters. Codes are either:
999MC111
or just
999MC
There is ALWAYS 2 Alpha characters. BUT there may be 1-4 characters at the front and sometimes 1-4 characters at the end.
If the code ENDS with the Alpha characters, then I run a certain ajax script. If there are Numbers + 2 letters + numbers....it runs a different ajax script.
My struggle is I know \d is for 2 digits....but it may not always be 2 digits.
So what would my regex code be to split this into an array. or something.
I think correct regex would be (/^([0-9]+)([a-zA-z]+)([0-9]+)$/
But how do i make sure its ONLY 2 alpha characters in middle?
Thanks
You could use the regex /\d$/ to determine if it ends with a decimal.
\d matches a decimal character, and $ matches the end of the string. The / characters enclose the expression.
Try running this in your javascript console, line by line.
var values = ['999MC111', '999MC', '999XYZ111']; // some test values
// does it end in digits?
!!values[0].match(/\d$/); // evaluates to true
!!values[1].match(/\d$/); // evaluates to false
To specify the exact number of tokens you must use brackets {}, so if you know that there are 2 alphabetic tokens you put {2}, if you know that there could be 0-4 digits you put {0,4}
^([0-9]{0,4})([a-zA-z]{2})([0-9]{0,4})$
The above RegEx evaluates as follows:
999MC ---> TRUE
999MC111 --> TRUE
999MAC111 ---> FALSE
MC ---> TRUE
The splitting of the expression into capturing groups is done by means of grouping subexpressions into parentheses
As you can see in the following link:
http://regexr.com?2vfhv
you obtain this:
3 capturing groups:
group 1: ([0-9]{0,4})
group 2: ([a-zA-z]{2})
group 3: ([0-9]{0,4})
The regex /^\d{1,4}[a-zA-Z]{2}\d{0,4}$/ matches a series of 1-4 digits, followed by a series of 2 alpha characters, followed by another series of 0-4 digits.
This regex: /^\d{1,4}[a-zA-Z]{2}$/ matches a series of 1-4 digits, followed only by 2 alpha characters.
Ok so I didnt really care about the middle 2 characters....all that really mattered was the 1st set of numbers and last set of numbers (if any).
So essentially I just needed to deal with digits. So I did this:
var lead = '123mc444'; //For example purposes
var regex = /(\d+)/g;
var result = (lead.match(regex));
var memID = result[0]; //First set of numbers is member id
if(result[1] != undefined) {
var leadID = result[1];
}