Why this match fail? - javascript

I have this code :
var tlTemp=new Array();
tlTemp.push("00 - 01:??:?? - TL 1");
tlTemp.push("00 - 12:??:?? - TL 2");
for(i=0; i<tlTemp.length; i++) {
var removedTL = tlTemp[i].match(/^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/);
if(removedTL!=null) {
alert("ok");
}
else
{
alert("no");
return;
}
}
and I don't understand why first string print ok and the second (so similar) no. Why?

The appropriate part of the regexp that defines the different part of the string is:
(\?\?|10|0\d)
It matches:
??
10
0x where x is a digit
So 12 does not match.
Now, also there is TL 2 instead of TL 1 but in the regexp this is defined as:
(.*)
which matches everything so that is not causing the problem.

Because your regular expression explicitly excludes it.
This section:
/^(\d\d) - (\?\?|10|0\d)
constrains matches to strings starting with two digits, a space, a dash, and a space, and then either "??", "10", or "0" followed by a digit.

This part of your regular expression: (\?\?|10|0\d) should be changed to (\?\?|10|\d\d). The zero is changed to a \d. in the first string, that part of the string is 01, while the second string has 12, not matching the regular expression.

Related

Regular expression to accept both positive and negative numbers

I need a regular expression that helps me to accept both positive and negative numbers
I have used ^-?\d*(.\d+)?$ expression
validateNegativeNumber(e: any) {
let input = String.fromCharCode(e.charCode);
const reg = /^-?\d*(.\d+)?$/;
if (!reg.test(input)) {
e.preventDefault();
}
}
Expected result: 5, +5, -5, 0
Unexpected results: 1.5, -1.5, 5++++, ++5, ---5, 5--, 50--6
You missed checking for + sign. Also there is no need for capturing groups.
Use this:
^[+-]?\d+$
An optional + or - sign at the beginning
Followed by one or more digits till the end
Demo
You can use the pattern attribute of input tag in HTML, like below:
<input pattern="^[+-]?\d+$">
Explanation: pattern attribute is available, it is better use rather than calling a function that validates the input. That will be an extra work.
I hope it helps.
Use this, for accept positive or negative both number.
^-?[0-9]\d*(\.\d+)?$
^[+-]?\d+(?:\.\d+)?$
Explanation:
^ matches the beginning of the string (so "abc212" will not validate)
[+-]? the first allowed char che be + o - matching 0 or 1 occurrence (the ?). Note that if you don't want the + sign, you can just write -?, so the regex will validate matching 0 or 1 occurrence of - as first char
\d+ after that you can have any number of digits (at least one, because we user the +)
(?:\.\d+)? at the end we can have 0 or 1 occurrence (given by the ?) of a dot (\.) followed by any number of digits (\d+). Note that the ?: at the beginning of the group says that this is a "non-capturing group")
$ matches the ending of the string (so "231aaa" will not validate)
How about this one?
const reg = /^[+-]?\d*(\.\d+)?$/;
const valids = ['+5', '-5', '5', '-5', '-0.6', '.55', '555.124'];
const invalids = ['--5', '5+', '5-'];
console.log('testing for valids array');
valids.forEach(valid => {
console.log(reg.test(valid));
});
console.log('testing for invalids array');
invalids.forEach(invalid => {
console.log(reg.test(invalid));
});

Regex for getting only the last N numbers in javascript

I've being trying to generate a regex for this string:
case1: test-123456789 should get 56789
case2: test-1234-123456789 should get 56789
case3: test-12345 should fail or not giving anything
what I need is a way to get only the last 5 numbers from only 9 numbers
so far I did this:
case.match(/\d{5}$/)
it works for the first 2 cases but not for the last one
You may use
/\b\d{4}(\d{5})$/
See the regex demo. Get Group 1 value.
Details
\b - word boundary (to make sure the digit chunks are 9 digit long) - if your digit chunks at the end of the string can contain more, remove \b
\d{4} - four digits
(\d{5}) - Group 1: five digits
$ - end of string.
JS demo:
var strs = ['test-123456789','test-1234-123456789','test-12345'];
var rx = /\b\d{4}(\d{5})$/;
for (var s of strs) {
var m = s.match(rx);
if (m) {
console.log(s, "=>", m[1]);
} else {
console.log("Fail for ", s);
}
}
You can try this:
var test="test-123456789";
console.log((test.match(/[^\d]\d{4}(\d{5})$/)||{1: null/*default value if not found*/})[1]);
This way supports default value for when not found any matching (look at inserted comment inline above code.).
You can use a positive lookbehind (?<= ) to assert that your group of 5 digits is preceeded by a group of 4 digits without including them in the result.
/(?<=\d{4})\d{5}$/
var inputs = [
"test-123456789", // 56789
"test-1234-123456789", // 56789
"test-12345", //fail or not giving anything
]
var rgx = /(?<=\d{4})\d{5}$/
inputs.forEach(str => {
console.log(rgx.exec(str))
})

Parse query parameters with regexp

I need to parse the url /domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2
and get 2 groups: 'a.b.c' and 'a.b.d'.
I try to parse with regexp [\?&]filter\[(.+\..+)+\]= but the result is 'a.b.c]=value1&filter[a.b.d'. How can I specify to search for the 1st occurrence?
You may use
/[?&]filter\[([^\].]+\.[^\]]+)]=/g
See the regex demo
Details
[?&] - a ? or &
filter\[ - a filter[ substring
([^\].]+\.[^\]]+) - Capturing group 1:
[^\].]+ - 1 or more chars other than ] and .
\. - a dot
[^\]]+ - 1 or more chars other than ]
]= - a ]= substring
JS demo:
var s = '/domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2';
var rx = /[?&]filter\[([^\].]+\.[^\]]+)]=/g;
var m, res=[];
while(m=rx.exec(s)) {
res.push(m[1]);
}
console.log(res);
Note that in case & is never present as part of the query param value, you may add it to the negated character classes, [^\].]+ => [^\]&.]+, to make sure the regex does not overmatch across param values.
Since you need to extract text inside outer square brackets that may contain consecutive [...] substrings with at least 1 dot inside one of them, you may use a simpler regex with a bit more code:
var strs = ['/domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2',
'/domain.com?filter[a.b.c]=value1&filter[a.b.d]=value2&filter[a][b.e]=value3',
'/domain.com?filter[a.b.c]=value1&filter[b][a.b.d][d]=value2&filter[a][b.e]=value3'];
var rx = /[?&]filter((?:\[[^\][]*])+)=/g;
for (var s of strs) {
var m, res=[];
console.log(s);
while(m=rx.exec(s)) {
if (m[1].indexOf('.') > -1) {
res.push(m[1].substring(1,m[1].length-1));
}
}
console.log(res);
console.log("--- NEXT STRING ----");
}
(?<=[\?&]filter\[)([^\]]+\.[^\]]+)+(?!>\]=)
This will give you only the groups you mentioned (a.b.c and a.b.d)
This part (?<=[\?&]filter\[) says recognise but don't capture [?&]filter before what you want and this part (?!>\]=) says recognise but don't capture after ] after what you want.
[^\]] this captures everything that isn't a square bracket

How to fetch only numbers which are not starting with 2 using regex in javascript?

I have a list of numbers like the following one:
200
302
301
201
205
500
Using regex, how can I fetch only the numbers which don't start with 2?
So the output should looks like :
302
301
500
Brief
There are multiple ways to accomplish this (presented below).
Note: I know the patterns only match the first character. Please read the entire answer to understand why (and how to match the full number if that's needed).
Code
The Usage section uses the first regex from each method (as it's a simple validation on the first character). The second regex from each method allows you to capture the entire number if that's the intention.
Method 1 - Regex: Character set
This method takes 39 steps and is 9 (+3) characters long.
See regex in use here
\b[013-9]
\b[013-9]\d*
Method 2 - Regex: Negative lookahead
This method takes 63 steps and is 9 (+1) characters long.
See regex in use here
\b(?!2)\d
\b(?!2)\d*
Method 3 - Regex: Negated character set
This method takes 39 steps and is 8 (+3) characters long.
See regex in use here
\b[^\D2]
\b[^\D2]\d*
Method 4 - JavaScript: startsWith
startsWith("2");
Method 5 - JavaScript: Array element
Assuming n is the number converted to a string.
n[0] !== "2"
Method 6 - JavaScript: Math
Assuming n is a positive number (we make it positive for the validation).
while(n >= 10) {
n = Math.floor(n/10);
}
if(n !== 2)
Usage
var nums = [200,302,301,201,205,500];
console.log("Method 1");
var r = /\b[013-9]/g
nums.forEach(function(s){
s = s.toString();
if(s.match(r)) {
console.log(s);
}
});
console.log("\nMethod 2");
var r = /\b(?!2)\d/g
nums.forEach(function(s){
s = s.toString();
if(s.match(r)) {
console.log(s);
}
});
console.log("\nMethod 3");
var r = /\b[^\D2]/g
nums.forEach(function(s){
s = s.toString();
if(s.match(r)) {
console.log(s);
}
});
console.log("\nMethod 4");
nums.forEach(function(s){
s = s.toString();
if(!s.startsWith("2")) {
console.log(s);
}
});
console.log("\nMethod 5");
nums.forEach(function(s){
s = s.toString();
if(s[0] !== "2") {
console.log(s);
}
});
console.log("\nMethod 6");
nums.forEach(function(s){
var n = Math.abs(s);
while(n >= 10) {
n = Math.floor(n/10);
}
if(n !== 2) {
console.log(s);
}
});
Results
Input
200
302
301
201
205
500
Output
302
301
500
Explanation
Note: All the regular expressions in my answer use \b (word boundary) to ensure the start of the number. You can replace this with your needs. If the input is multiline, for example, you may want to use ^ (start of line assertion) with the multiline flag (typically m). The below explanations exclude the explanation of the \b token (since I've already explained it).
Method 1 - Regex: Character set
[013-9] Match a character in the set (0, 1, or a number in the range of 3-9)
Method 2 - Regex: Negative lookahead
(?!2)\d Negative lookahead ensuring what follows is not a 2.
Method 3 - Regex: Negated character set
[^\D2] Match any character not in the set (any non-digit or 2). Note that [^\D2] is actually a double negative that means match any digit, excluding 2
Method 4 - JavaScript: startsWith
From Mozilla's documentation:
Syntax
str.startsWith(searchString[, position])
Parameters
searchString
The characters to be searched for at the start of this string.
position Optional
The position in this string at which to begin searching for searchString; defaults to 0.
Return value
true if the given characters are found at the beginning of the
string; otherwise, false.
Description
This method lets you determine whether or not a string begins with
another string. This method is case-sensitive.
Method 5 - JavaScript: Array element
This method is simply taking the first digit in a number and testing it against the string 2 to see if they match. Anything that returns false is returned (does not start with 2).
Method 6 - JavaScript: Math
This method gets the absolute value of a number Math.abs() and then continuously divides the number by 10 while removing decimal places (Math.floor(n/10)) until the number is less than 10. The result is then checked against the number 2 to ensure it doesn't match if(n !== 2).

Detect repeating letter in an string in Javascript

code for detecting repeating letter in a string.
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting "false" as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr". i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE" when the character repeats in a string
JSFIDDLE
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
If you have a requirement that the second match must be at the end-of-the-string then you can add $ to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary.
Try this:
var str = "paraven4sr";
function checkDuplicate(str){
for(var i = 0; i < str.length; i++){
var re = new RegExp("[^"+ str[i] +"]","g");
if(str.replace(re, "").length >= 2){
return true;
}
}
return false;
}
alert(checkDuplicate(str));
Here is jsfiddle
To just test duplicate alphanumeric character (including underscore _):
console.log(/(\w)\1+/.test('aab'));
Something like this?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
"aab".count("a") > 1
EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. Anyway, I leave this function here, maybe it can help. Sorry ;)

Categories

Resources