compose a javascript expression that has one uppecase letter and six numbers - php

I need to compose a regular JavaScript expression. This expression is based on a serial number The parameters of the expression is this:
One Uppercase Letter at the beginning and the rest of the expression is digits (6)
Example: E234585, C345678, E001234
Thanks for your assistance

Try this expression:
/^[A-Z]\d{6}$/
This will match serial numbers in the format you described.
[A-Z] matches the first uppercase letter, then \d{6} matches the following 6 digits. The anchors (^ and $) ensure the matched string contains only the serial number and nothing else.

Your question is very unclear, I'm going to take a stab in the dark and assume you meant you wanted to generate those random strings:
var getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var getRandomLetter = function () {
return String.fromCharCode(getRandomInt(65, 90));
};
var getRandomDigit = function () {
return getRandomInt(0, 9);
};
var yourString = getRandomLetter() + getRandomDigit() + ... + getRandomDigit();

​var serialre = new RegExp('[A-Z]{1}[0-9]{6}');​​​​​​​​​​​​​​​​​​​​​​​​
if(serialre.test('A123456')){
document.write('yep');
} else {
document.write('nope');
}
document.write('<br />');
if(serialre.test('POOPSTAINS!')){
document.write('yep');
} else {
document.write('nope');
}
​
Produces:
yep
nope
Check out the JSFiddle

Related

Regex to match four blocks ranges [duplicate]

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.
For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.
Use the start and end delimiters: ^abc$
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b (word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

PHP Regex: match specific length of string on repeated char [duplicate]

I am trying to write a regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings "(" and ")"
I expect five hundred dollars ($500).
would return
$500
Found Regular expression to get a string between two strings in Javascript
I don't know how to use '(', ')' in regexp.
You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");
//matches[1] contains the value between the parentheses
console.log(matches[1]);
Breakdown:
\( : match an opening parentheses
( : begin capturing group
[^)]+: match one or more non ) characters
) : end capturing group
\) : match closing parentheses
Here is a visual explanation on RegExplained
Try string manipulation:
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
console.log(newTxt[i].split(')')[0]);
}
or regex (which is somewhat slow compare to the above)
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
var str = matches[i];
console.log(str.substring(1, str.length - 1));
}
Simple solution
Notice: this solution can be used for strings having only single "(" and ")" like string in this question.
("I expect five hundred dollars ($500).").match(/\((.*)\)/).pop();
Online demo (jsfiddle)
To match a substring inside parentheses excluding any inner parentheses you may use
\(([^()]*)\)
pattern. See the regex demo.
In JavaScript, use it like
var rx = /\(([^()]*)\)/g;
Pattern details
\( - a ( char
([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
\) - a ) char.
To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.
Most up-to-date JavaScript code demo (using matchAll):
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
const matches = [...x.matchAll(rx)];
console.log( Array.from(matches, m => m[0]) ); // All full match values
console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
Legacy JavaScript code demo (ES5 compliant):
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;
for (var i=0;i<strs.length;i++) {
console.log(strs[i]);
// Grab Group 1 values:
var res=[], m;
while(m=rx.exec(strs[i])) {
res.push(m[1]);
}
console.log("Group 1: ", res);
// Grab whole values
console.log("Whole matches: ", strs[i].match(rx));
}
Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.
var matches = string2.split('[')
.filter(function(v){ return v.indexOf(']') > -1})
.map( function(value) {
return value.split(']')[0]
})
Alternative:
var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
→ (2) ["$500", "$1"]
It is possible to replace brackets with square or curly brackets if you need
For just digits after a currency sign : \(.+\s*\d+\s*\) should work
Or \(.+\) for anything inside brackets
let str = "Before brackets (Inside brackets) After brackets".replace(/.*\(|\).*/g, '');
console.log(str) // Inside brackets
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));
Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
alert(matches[i]);
}
This code alerts with all the matches.
References:
search for "?=n"
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
search for "x(?=y)"
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Simple:
(?<value>(?<=\().*(?=\)))
I hope I've helped.

Preg_match find numbers in string after Dash [duplicate]

i have a id like stringNumber variable like the one as follows : example12
I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.
This regular expression matches numbers at the end of the string.
var matches = str.match(/\d+$/);
It will return an Array with its 0th element the match, if successful. Otherwise, it will return null.
Before accessing the 0 member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle.
If you must have it as a Number, you can use a function to convert it, such as parseInt().
number = parseInt(number, 10);
RegEx:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
String manipulation:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);

customizing preg_match

How do i preg_match an string to match the following format in php:
$m="123/456789/01";
if(pregmatch(????, $m){
// match
}else{
// doesn't match
}
i.e. 3 digits + "/" + 6 digits + "/" + 2 digits.
This is my try :)
if(preg_match('/[0-9]{3}\/[0-9]{6}\/[0-9]{2}/', $m)
{
// match
}
else
{
// Doesn't match
}
if (preg_match("#\d{3}/\d{6}/\d{2}#", $string)) {
// yeah
} else {
// nope
}
have a look at Pattern Syntax specifically Escape sequences.
Depending on what you would like to parse, regular expressions are not always needed:
$m="123/456789/01";
if(3 == count(sscanf($m, '%d/%d/%d'))) {
// match
}else{
// doesn't match
}

Regex - Strip non numeric and remove cents if any

I'm currently working on a project in PHP and I'm in need of some Regex help. I'd like to be able to take a user inputted monetary value and strip all non numeric and decimal places/cents.
Ex:
'2.000,00' to '2000'
'$ 2.000,00' to '2000'
'2abc000' to '2000'
'2.000' to 2000
(I'm using non US currency formatting)
How can I do this? I'd appreciate the help - Thanks
You can do:
$str = preg_replace('/[^0-9,]|,[0-9]*$/','',$str);
$output = preg_replace('/[^0-9]/s', '', $input);
that should replace non numeric chars with empty strings.
This should do what you want.
$your_string_without_letters = preg_replace('\w+', '', $your_string)
preg_match('[0-9][0-9.]*', $your_string_without_letters, $matches);
$clean_string = $matches[0];
The match will start as soon as the first number is found, and stop when it hits something that is neither a number nor a dot (ie. a comma or the end of the string in your examples)
EDIT : forgot to remove the letters inside the value first.
(Just a personal opinion, but if a user writes chracters that are not numbers, dots, commas or currency symbols I would refuse the input instead of trying to clean it)
On the client side I use classes on the inputs:
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
$("input.money").keyup(function(){ money($(this)) })
.blur(function(){ money($(this),1); });
//----------- free-standing functions --------------
function money($inElem,inBlur,inDec){//enforces decimal - only digits and one decimal point. inBlur bool for final slicing to sets of 3 digits comma delimted
var isBlur=inBlur||0;//expects boolean (true/false/0/1 all work), default to 0 (false)
var dec=inDec || 2;
if(/[^,.0-9]/g.test($inElem.val()))//if illegal chars, remove and update
$inElem.val($inElem.val().replace(/[^,.0-9]/g, ""));
var ra=$inElem.val().split(".");
if(ra.length>2 || ra.length>1 && ra[ra.length-1].length>2){//if too more than 1 "." or last segment more than dec digit count, fix and update
if(ra[ra.length-1].length>2) ra[ra.length-1]=ra[ra.length-1].substr(0,dec);//shorten last element to only dec digit count
$inElem.val(ra.slice(0,ra.length-1).join("")+"."+ra[ra.length-1]);//glom all but last elem as single, concat dec pt and last elem
}
if(inBlur){
ra=$inElem.val().split(".");
var rvsStr=zReverse(ra[0].replace(/,/g,""));
var comDelim="";
while(rvsStr.length>0){
comDelim+=rvsStr.substr(0,3)+",";
rvsStr=rvsStr.substr(3);
}
$inElem.val(zReverse(comDelim).substr(1)+(ra.length==2?"."+ra[1]:""));
}
}
function zReverse(inV){//only simple ASCII - breaks "foo 𝌆 bar mañana"
return inV.split("").reverse().join("");
}

Categories