Java script regular expression a bit confusing [duplicate] - javascript

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 3 years ago.
I am actually new to javascript and I'm trying to understand what went wrong with this code.
I have a function that accepts a abc as a parameter.
This regular expression was given to me by one of my colleges. I don't have any idea what it's doing.
Just wanted to understand what is the return statement here.
(function(abc) {
var match = abc.match(/(\d+).+?(\d+)/);
return +match[2] + 1;
});
I think the match will contain digits in decimal format but not clear about it.
what will this return? Please let me understand this, will be a great help.

(\d+) - one or more digits (0-9)
.+? - one or more periods (.)
(\d+) - one or more digits (0-9)
Debuggex Demo

You can easily create a snippet and debug it. Using provided example:
function getDiskInfo(diskinfo) {
var match = diskinfo.match(/(\d+).+?(\d+)/);
return +match[2] + 1;
}
console.log(getDiskInfo('111.222'));
In this example, as described by #phuzi:
var match = ['111.222', '111', '222'];
After that your return statement cast your element with index = 2 to Number and increments it by one. So using my example the final result will be 223.

Related

Trying to extract matches from a string matching an expression in JavaScript [duplicate]

This question already has answers here:
Regex to Get Phone Numbers From String
(3 answers)
Closed 10 months ago.
I have spent two days on this and I can't figure it out. Sorry to sound specific. I am trying to match phone numbers in a string and store them in an array. For example:
// An example string
let string = "30000 loaves of bread were purchased by +1777654352"
// I got this from https://ihateregex.io/expr/phone/ and it works for my purpose
const regex = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/gmi
// I expect found to have [+1777654352]
const found = string.match(regex);
Instead, I keep getting null in my found array. I am not sure what I am doing wrong. I hope someone out there can point me in the right direction.
this regex has ^ on the beginning and $ in the end so I'm pretty sure it matches only on phone numbers that are separated by line breaks, or that are alone in their String.
This regex should work for your needs:
let string = "30000 loaves of bread were purchased by +1777654352"
const regex = /[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}/gmi;
const found = string.match(regex);
Silly me!
I was using the regular expression poorly. Using the ^ and $ flags were causing the issue. They signify the start and end of the string and hopefully someone can explain why it behaves that way. Removing those made string.match(regex) work as expected.

Regex pattern for //;\n2;3;4 [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 1 year ago.
I am trying to find a regex which supports a pattern like below:
String starts with //
String has a delimiter after //; (suppose ; is the delimiter)
String has \n after demiliter (//;\n)
Finally String contains any number of digits with that delimiter (//;\n2;3;4;5)
Could you help?
I tried ^//\\D+\\n.*$ but it doesn't work.
Thanks in advance!
Sample: //;\n2;3;4;5
Answer: [/]{2}[;]\\[n](\d[;]){1,999}\d
This will allow further combinations of a decimal followed by ;
\d is added at the end in the case a semicolon is not added judging by your sample
Okay based on your additional comment this could work. It's very messy but it may just get the job done.
var string = "//;\n2;3;4;5";
console.log(
string.replace(/[^0-9,.]+/g," ").trim().split(" ").map(function(x){return parseInt(x, 10);}).reduce(function(a, b){return a + b;}, 0)
);
Console log results in 14

Getting a true or false reply to a Regex match? [duplicate]

This question already has answers here:
Return true/false for a matched/not matched regex
(5 answers)
Closed 3 years ago.
I'm trying to match an entire string against a regex formula. This is for validating if a phone number field is likely correct (just based on allowed characters, anyone can make up an number). I've played with Regex before but never truly understood the nuances that make it powerful.
Below I have my dummy phone number and I have the regex I'm using. As you can see I'm simply comparing the length of the match vs the length of the string and if they match the number must be valid.
Is there a way to get a simple true/false reply from a Regex check on an entire string?
var num = '+1 (888) 456-7896';
var regex = /[0-9+ ()-]*$/;
var found = num.match(regex);
console.log(found[0].length);
console.log(num.length);
You can use test()
var found = regex.test(num);

How do I properly use RegExp in JavaScript and PHP? [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 6 years ago.
How do I properly use RegExp?
var text = "here come dat boi o shit waddup";
var exmaple = /[a-zA-Z0-9 ]/; // allowes a-zA-Z0-9 and whitespaces but nothing else right?
example.test(test); // would return true right?
text = "%coconut$ยง=";
example.test(text); // would return false right?
//I know this is very basic - I started learnig all this about week ago
Are JS RegExp's the same as PHP RegExp's?
How do I define banned characters instead of defining allowed characters?
How do I make it so that the var text has to contain 3 (or more) numbers/letters?
How do I include / or ",'$ etc. in my pattern?
No.
Use ^ character (i.e. [^abc] will exclude a, b and c)
Use [A-Za-z]{3} for letters and \d{3} for digits. If you want 3 or more, use \d{3,}
Use escape character (\/, \', \", '\$')

What does "matches x and remembers the match" means in regexp [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 8 years ago.
Pardon me if it seems to be trivial but just to understand regexps:
As said here with character (x) :
(x) matches x and remembers
First part "matches" I can understand but the second part "remembers" is a bit tedious for me to understand.
Can someone please help in explaining it in much easier way?
It's called capturing group. Using backreference ($1, $2, ...), you can reference it in the substitution string:
'R2D5'.replace(/(\d)/g, '$1$1')
// => "R22D55"
You can also use backreference (\1, \2, ...) in the pattern:
'ABBCCDEF'.match(/(.)\1/g) // to match consecutive character
// => ["BB", "CC"]
And you will get additional parameters when you use replacement function:
'R2D5'.replace(/(\d)/g, function(fullMatch, capture1) {
return (parseInt(capture1) + 1).toString();
})
// => "R3D6"
In most regex stuff you can specify a "capturing group" and recall them later:
"something".replace(/so(me)/, '$1 ')
Here, the capturing group is (me) - the result will be me thing

Categories

Resources