Difference between these regular expressions? - javascript

I want a regular expression that matches numbers from 1 to 100.
This works:
var regNumeric = /^(100|[1-9][0-9]|[1-9])$/;
But this does't
var regNumeric = /^100|[1-9][0-9]|[1-9]$/;
Why?
Code:
var value = '121' ;
var regNumeric = /^(100|[1-9][0-9]|[1-9])$/;
if(regNumeric.test(value)){
// Match
}

Why this works?
/^(100|[1-9][0-9]|[1-9])$/
Because of the parentheses it will apply start ^ and end $ anchors to each of the pattern separated by OR |.. which is equivalent to.. ^100$ or ^[1-9][0-9]$ or ^[1-9]$
Why this doesn't?
/^100|[1-9][0-9]|[1-9]$/
This regex is equivalent to ^100 or [1-9][0-9] or [1-9]$ (observe the anchors). So this would match unnecessary requirements like 100abc or hey13s or batman5

Related

Finding ++ in Regular Expression

I want to find ++ or -- or // or ** sign in in string can anyone help me?
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = ++,--,//,**;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
This finds doubles of the characters by a backreference:
/([+\/*-])\1/g
[from q. comments]: i know this but when i type var patt1 = /[++]/i; code find + and ++
[++] means one arbitrary of the characters. Normally + is the qantifier "1 or more" and needs to be escaped by a leading backslash when it should be a literal, except in brackets where it does not have any special meaning.
Characters that do need to be escaped in character classes are e.g. the escape character itself (backslash), the expression delimimiter (slash), the closing bracket and the range operator (dash/minus), the latter except at the end of the character class as in my code example.
A character class [] matches one character. A quantifier, e.g. [abc]{2} would match "aa", "bb", but "ab" as well.
You can use a backreference to a match in parentheses:
/(abc)\1
Here the \1 refers to the first parentheses (abc). The entire expression would match "abcabc".
To clarify again: We could use a quantifier on the backreference:
/([+\/*-])\1{9}/g
This matches exactly 10 equal characters out of the class, the subpattern itself and 9 backreferences more.
/.../g finds all occurrences due to the modifier global (g).
test-case on regextester.com
Define your pattern like this:
var patt1 = /\+\+|--|\/\/|\*\*/;
Now it should do what you want.
More info about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
You can use:
/\+\+|--|\/\/|\*\*/
as your expression.
Here I have escaped the special characters by using a backslash before each (\).
I've also used .test(str) on the regular expression as all you need is a boolean (true/false) result.
See working example below:
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = patt1.test(res);
if (result) {
alert("you cant do this :l");
document.getElementById('screen').innerHTML = '';
}
<div id="screen">
This is some++ text
</div>
Try this:-
As
n+:- Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
We need to use backslash before this special characters.
var str = document.getElementById('screen').innerHTML;
var res = str.substring(0, str.length);
var patt1 = /\+\+|--|\/\/|\*\*/;
var result = str.match(patt1);
if (result)
{
alert("you cant do this :l");
document.getElementById('screen').innerHTML='';
}
<div id="screen">2121++</div>

Extract word between '=' and '('

I have the following string
234234=AWORDHERE('sdf.'aa')
where I need to extract AWORDHERE.
Sometimes there can be space in between.
234234= AWORDHERE('sdf.'aa')
Can I do this with a regular expression?
Or should I do it manually by finding indexes?
The datasets are huge, so it's important to do it as fast as possible.
Try this regex:
\d+=\s?(\w+)\(
Check Demo
in Javascript it would like that:
var myString = "234234=AWORDHERE('sdf.'aa')";// or 234234= AWORDHERE('sdf.'aa')
var myRegexp = /\d+=\s?(\w+)\(/g;
var match = myRegexp.exec(myString);
console.log(match[1]); // AWORDHERE
You could do this at least three ways. You need to benchmark to see what's fastest.
Substring w/ indexes
function extract(from) {
var ixEq = from.indexOf("=");
var ixParen = from.indexOf("(");
return from.substring(ixEq + 1, ixParen);
}
.
Splits
function extract(from) {
var spEq = from.split("=");
var spParen = spEq[1].split("(");
return spParen[0];
}
Regex (demo)
Here is some sample regex you could use
/[^=]+=([^(]+).*/g
This says
[^=]+ - One or more character which is not an =
= - The = itself
( - creates a matching group so you can access your match in code
[^(]+ - One or more character which is not a (
) - closes the matching group
.* - Matches the rest of the line
the /g on the end tells it to perform the match on all lines.
Using look around you can search for string preceded by = and followed by ( as following.
Regex: (?<==)[A-Z ]+(?=\()
Explanation:
(?<==) checks if [A-Z ] is preceded by an =.
[A-Z ]+ matches your pattern.
(?=\() checks if matched pattern is followed by a (.
Regex101 Demo
var str = "234234= AWORDHERE('sdf.'aa')";
var regexp = /.*=\s+(\w+)\(.*\)/g;
var match = regexp.exec(str);
alert( match[1] );
I made my solution for this just a little more general than you asked for, but I don't think it takes much more time to execute. I didn't measure. If you need greater efficiency than this provides, comment and I or someone else can help you with that.
Here's what I did, using the command prompt of node:
> var s = "234234= AWORDHERE('sdf.'aa')"
undefined
> var a = s.match(/(\w+)=\s*(\w+)\s*\(.*/)
undefined
> a
[ '234234= AWORDHERE(\'sdf.\'aa\')',
'234234',
'AWORDHERE',
index: 0,
input: '234234= AWORDHERE(\'sdf.\'aa\')' ]
>
As you can see, this matches the number before the = in a[1], and it matches the AWORDHERE name as you requested in a[2]. This will work with any number (including zero) spaces before and/or after the =.

regular expression for numeric value; at most 3 decimal places

I'm trying to validate a form using regular expressions, the conditions are:
It has to be a numeric value
It CAN have up to three decimal places(0,1,2 are allowed too)
It has to be divided by a comma(,)
I already got it to work using HTML5-Patterns with this:
pattern='\d+(,\d{1,3})?'
Since patterns are not supported by IE9, I tried doing it with js:
var numPattern = /\d+(,\d{1,3})?/;
if(!numPattern.test(menge.val()))
{
checkvalidate = false;
}
Where did I go wrong?
Examples
valid: 1,234 ; 2,00 ; 5 ; 0,1
invalid: 1,2345 ; 2.00 ; 56a
You'll need to start your regex with ^ and end it with $ to make sure the entire input string/line is matched.
/^\d+(,\d{1,3})?$/
Here's a "demo" in which all your examples are valid/invalid:
https://regex101.com/r/oP5yJ4/1
(Using regex101.com to debug your regular expression patterns is often very useful)
Note that: (without ^ and $)
var pattern_without = /\d+(,\d{1,3})?/;
pattern_without.test("56a") === true; // matches, but only "56"
pattern_without.test("1,2345") === true; // matches, but only "1,234"
but: (with ^ and $)
var pattern_with = /^\d+(,\d{1,3})?$/;
pattern_with.test("56a") === false; // no match
pattern_with.test("1,2345") === false; // no match
You can use this regex:
/^\d+(?:,\d{1,3})*$/
RegEx Demo
Try this expression:
\d+(,\d{3})*([.]\d{1,3})?
Valid examples:
1,200.123
1,200.12
1,200.1
1.123
1,200,222
1,200,002
You can use the RegExp object.
var str = "123545,123";
var patt = new RegExp("/^(?:\d*\,\d{1,3}|\d+)$/");
var res = patt.test(str);
After execution, res will be true, since str matches the pattern you're looking for,

JS: Regular expression to find all function calls in the body of a function

I would need a regular expression to return the parameter of a function that begins with APP("name")
So in this example only the second line would match and it would return me the text -name-
testing text:
var w = app("name").test
var x = APP("name").test()
var y = SNAPP("name").test()
var z = APPLICATION("name").test()
I tried some things out but it's not working: http://www.regexr.com/3a1h2
thx,
Regex:
\bAPP\("([^")]+)
Try this.See demo.Grab the string you want from group index 1.
https://regex101.com/r/aQ3zJ3/3
> var s = 'var x = APP("name").test()';
undefined
> console.log(/\bAPP\("([^")]+)/.exec(s)[1]);
name
You just need to add a word boundary and you must need to escape the () brackets so that it would match a literal ( , ) symbols.
/\bAPP\(([^()]*)\)/
\b word boundary which matches between a word character and a non-word character. Get the string you want from group index 1.
DEMO
> var s = 'var x = APP("name").test()';
> console.log(/\bAPP\(([^()]*)\)/.exec(s)[1]);
"name"
Try this:
\sAPP\(\s*\S.*\)
You are picking up SNAPP() as well as APP()
The \s checks for a space before the name of the function

Replace string that starts with specific character and ends with specific character in regular expression

I wanted to replace a string section that starts with a specific character and ends with specific character. At below, I demonstrate test case.
var reg = /pattern/gi;
var str = "asdfkadsf[xxxxx]bb";
var test = str.replace(reg,"") == "asdfkadsfbb"
console.log(test);
This pattern should work for replace anything between brackets (including the brackets):
var reg = /(\[.*?\])/gi;
var str = "asdfkadsf[xxxxx]bb";
var test = str.replace(reg,"") == "asdfkadsfbb"
based on your example, this works:
/\[.*]/gi

Categories

Resources