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.
Related
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
I have this autogenerated variable:
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
How can I search and save "9999" in this var? I cant use substr cause $var's value is always changing and it is always in another "place" in the variable. It is always 4 numbers.
You can match 4 numbers wrapped by word boundaries or space characters, depending on what you need with regular expression (regex/regexp).
if( preg_match('/\b([0-9]{4})\b/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Note, however, that the word boundary match will also match on non-letter characters (symbols like dollar sign ($), hyphen (-), period (.), comma (,), etc.). So a string of "XYZ ABC 9843-AB YZV" would match the "9843". If you want to just match based on numbers surrounded by white space (spaces, tabs, etc) you can use:
if( preg_match('/(?:^|\s)([0-9]{4})(?:\s|$)/', $var, $matches) > 0 ) {
// $matches[1] contains the number
}
Using explode is the way to go, we need to turn the string into an array, our variables are separated by white space, so we get a variable every time we face a white space " ", i made another example to understand how explode works.
<?php
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
print_r (explode(" ",$var)); //Display the full array.
$var_search = explode(" ",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
<br>
<?php
$var = "WXYZ+300700Z+32011KT+9999+FEW035+SCT200+24/16+Q1007+NOSIG";
print_r (explode("+",$var)); //Display the full array.
$var_search = explode("+",$var);
echo $var_search[3];//To echo the 9999 (4th position).
?>
I hop this is what you're looking for
Is this viable?
$var = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
if (strpos($var, '9999') == true {
// blah blah
}
else{
echo 'Value not found'
}
Personally haven't tested this yet, but I think you're looking for something along these lines...
Hello I would use a preg_match regex using this regular expression : \d{4}
here is the solution
var str1 = "WXYZ 300700Z 32011KT 9999 FEW035 SCT200 24/16 Q1007 NOSIG";
var str2 = "9999";
if(str1.indexOf(str2) != -1){
console.log(str2 + " found");
}
i have this function in php :
$html_price = "text text 12 eur or $ 22,01 text text";
preg_match_all('/(?<=|^)(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] *)?)(?:\ |)(?:\$|usd|eur)+(?=|$)|(?:\$|usd|eur)(?:| )(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] *)?)/', strtolower($html_price), $price_array1);
print_r($price_array1);
Now i want use in javascript the same regex but i have an error:
SyntaxError: invalid quantifier
my javascript :
maxime_string = "((?<=|^)(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] *)?)(?:\ |)(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€)+(?=|$)|(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€)(?:| )(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] *)?))";
maxime_regex = new RegExp(maxime_string);
var text = "text text 12 eur or $ 22,01 text text";
var result = text.match(maxime_regex);
var max = result.length;
alert(result.length);
for (i = 0; i < max; i++)
{
document.write(result[i] + "<br/>");
}
Can you help me ?
JavaScript does not support lookbehind - that's probably where you got your error from. Some things:
(?<=|^) makes no sense. It's a lookbehind demanding either nothing or string begin to come before this - it's always true. And if you want to match the string start, use a single ^.
(?:.[0-9]*)? - I guess you wanted to escape the dot so it matches literally
(?:\ |): You do not need to escape blanks. And instead of an alternative "nothing", you should just make the blank optional: " ?".
(?=|$) makes as much sense as the first group.
€ is a broken unicode character?
Also, you should consider using a regex literal instead of the RegExp constructor with a string literal - it eats one level of backslash escaping. And it seems you're missing the global flag, so that you get back all matches. Try this:
var maxime_regex = /((?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:\.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] *)?) ?(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€)+|(?:\$|usd|eur|euro|euros|firm|obro|€|£|gbp|dollar|aud|cdn|sgd|€) ?(?:[0-9]{1,3}(?:,| ?[0-9]{3})*(?:\.[0-9]*)?|[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9] *)?))/g
This post does not include any effort to understand, optimize or shorten that regex monster
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
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("");
}