Find numbers that are in parentheses using regular expression and Javascript - javascript

There is such line
let str = 'ds 1,2abc{3,4}dd'
I need to find numbers that will be included in {} without enclosing the brackets themselves.
For example (Assuming that regex is a per-defined regular expression) I want to write something like the following.
(str.match(regexp)).join('').split(',')
Which will produce a result like this => ['3','4']
and if I have only one char in brackets or char with comma I need to get next result
let str = 'ds 1,2abc{3,}dd'
(str.match(regexp)).join('').split(',') => ['3','']
At the moment, I have such a regular const regexp = (/\d+\,\d*|(?<=\{)\d+/
but it does not handle the case when there are more numbers in the string with a comma like 1,2

It seems you are actually trying to include an empty string in your resulting array. Maybe you could use:
var str = 'ds 1,2abc{3,4}dd';
var res = str.split(/[{}]/)[1].split(",");
console.log(res)
var str = 'ds 1,2abc{3,}dd';
var res = str.split(/[{}]/)[1].split(",");
console.log(res)

The usual workaround, when the number of open/close curly braces is matching and you need not pre-validate your input, you may simply use
str.match(/\d+(?:\.\d+)?(?=[^{}]*})/g)
str.match(/\d*\.?\d+(?=[^{}]*})/g)
Here, \d+(?:\.\d+)?(?=[^{}]*}) matches 1+ digits, followed with an optional sequence of a dot and 1+ digits followed with 0 or more chars other than { and } and then a }.
See this demo
In a more generic case, you may extract groups of numbers inside curly braces by matching curly braces with comma-separated numbers in them first. Then, you may extract the numbers from each match:
const str = 'ds 1,2abc{3,4}dd{not this one 5,6} and {7,8.666,9,10.45}';
const rx = /{\d*\.?\d+(?:,\d*\.?\d+)*}/g;
const results = str.match(rx).map(x => x.replace(/[{}]+/g,'').split(','));
console.log( results );
See the regex demo.
{ - a { char
\d*\.?\d+ - 0 or more digits followed with an optional . and then 1+ digits
(?:,\d*\.?\d+)* - 0 or more repetitions of a comma followed with 0 or more digits followed with an optional . and then 1+ digits
} - a { char.

Related

Split characters in a string with a comma in javascript

I'm trying to write a regex function that return all of the digits in a comma separated string:
function printDigits() {
var result = sentence.replace(/[^0-9]/g, '').split(",")
console.log(result)
}
But it just prints out a string instead of digits being separated by comma. Are there any ways I can fix this?
Input: "5om3 wr173 w0rd5 u51n9 numb3r5."
Expected output: "5,3,1,7,3,0,5,5,1,9,3,5"
split doesn't work this way. It splits by the separator that is already in the input. To split string to individual characters use split(''), and then join individual characters with comma:
var result = sentence.replace(/[^0-9]/g, '').split('').join(',');
You can use
sentence.match(/\d/g).join(",")
Here,
sentence.match(/\d/g) - extracts each separate digit from string
.join(",") - join the array items into a single comma-delimited string.
See the JavaScript demo:
var sentence = "5om3 wr173 w0rd5 u51n9 numb3r5.";
console.log(sentence.match(/\d/g).join(","));
// -> 5,3,1,7,3,0,5,5,1,9,3,5
Here's another variation that uses pure regex and does not require a .join() call:
sentence.replace(/\D+|(\d)(?=\d)/g, '$1,');
This replaces any string of non-digit characters with a comma. And it also locates the position between two digits and adds a comma between them.
Pattern breakdown:
\D+ - Match one or more non-digit characters.
| - OR...
(\d) - Match one digit and capture it in group 1.
(?=\d) - Followed by another digit.
Substition:
$1, - Replace with whatever was captured in group 1, plus a comma.
Here's a full demo:
var sentence = "5om3 wr173 w0rd5 u51n9 numb3r5";
var result = sentence.replace(/\D+|(\d)(?=\d)/g, '$1,');
console.log(result); // 5,3,1,7,3,0,5,5,1,9,3,5
A reducer solution
const x = `5om3 wr173 w0rd5 u51n9 numb3r5`
.split('')
.reduce((acc, val) =>
val.trim().length && !isNaN(+val) ? [...acc, +val] : acc, []);
console.log(`${x}`);
Or simply
console.log(`${`5om3 wr173 w0rd5 u51n9 numb3r5`.match(/\d/g)}`);

Is it possible to have one regex that solves this task?

string = '1,23'
When a comma is present in the string, I want the regex to match the first digit (\n) after the comma e.g.2.
Sometimes the comma will not be there. When it's not present, I want the regex to match the first digit of the string e.g. 1.
Also, we can't reverse the order of the string to solve this task.
I am genuinely stuck. The only idea I had was prepending this: [,|nothing]. I tried '' to mean nothing but that didn't work.
You can match an optional sequence of chars other than a comma and then a comma at the start of a string, and then match and capture the digit with
/^(?:[^,]*,)?(\d)/
See the regex demo.
Details
^ - start of string
(?:[^,]*,)? - an optional sequence of
[^,]* - 0 any chars other than a comma
, - a comma
(\d) - Capturing group 1: any digit
See the JavaScript demo:
const strs = ['123', '1,23'];
const rx = /^(?:[^,]*,)?(\d)/;
for (const s of strs) {
const result = (s.match(rx) || ['',''])[1];
// Or, const result = s.match(rx)?.[1] || "";
console.log(s, '=>', result);
}

Regex match a sequence of numbers and a character . between them

So I need to get all ${{1.33.98}} strings from a string.
new RegExp('\\$\\{\\{(.*?)\\}\\}', 'g'); doesnt work well on case like:
${{1.33.98}${{2.44.1}} - should match only ${{2.44.1}} because ${{1.33.98} is missing } at this example.
So it shouldn't match if string missing any of the two {{ or two }} or $.
Between {{ and }} can be only a sequence of numbers separated by a dot - ex. 4.23.4545
Thanks
You match unwelcome values because . can match any char, and thus it matches any chars from the leftmost {{ to the first }} to the right of {{.
You may use
/\${{(\d[\d.]*)}}/g
Or, if the dot-separated number format is important
/\${{(\d+(?:\.\d+)*)}}/g
See this regex demo and this regex demo.
Note that if the strings are prevalidated, and you are sure there are no { and } inside ${{ and }}, you may even use [^{}]* instead of \d[\d.]*:
/\${{([^{}]*)}}/g
So, you either capture
\d[\d.]* - a digit and then 0 or more digits and dots
or
\d+(?:\.\d+)* - 1+ digits and then 0+ repetitions of . and 1+ digits.
JS demo:
const s = '${{1.33.98}${{2.44.1}} ${{1.24.52.44.1}}';
let m = [...s.matchAll(/\${{(\d[\d.]*)}}/g)];
console.log(Array.from(m, x => x[1]));
For legacy ES versions:
var s = '${{1.33.98}${{2.44.1}} ${{1.24.52.44.1}}';
var rx = /\${{(\d[\d.]*)}}/g, results = [], m;
while (m=rx.exec(s)) {
results.push(m[1]);
}
console.log(results);

Javascript Regex: Capture between two asterisks with multiple asterisks in comma delimited string

I am trying to capture all characters between multiple instances of asterisks, which are comma delimited in a string. Here's an example of the string:
checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*
The caveat is that the phrase must start and end with an asterisk. I have been able to come close by using the following regex, however, it won't discard any matches when the captured string is missing the starting asterisk(*):
let str = "checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*"
const regex = /[^\,\*]+(?=\*)/gi;
var a = str.match(regex)
console.log(a) // answer should exclude checkboxID0 and checkboxID5
The answer returns the following, however, "checkboxID0 and checkboxID5" should be excluded as it doesn't start with an asterisk.
[
"checkboxID0",
"checkboxID1",
"checkboxID3",
"checkboxID5"
]
Thanks, in advance!
You need to use asterisks on both ends of the pattern and capture all 1 or more chars other than commas and asterisks in between:
/\*([^,*]+)\*/g
See the regex demo
Pattern details
\* - an asterisk
([^,*]+) - Capturing group 1: one or more chars other than , and *
\* - an asterisk
JS demo:
var regex = /\*([^,*]+)\*/g;
var str = "checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*";
var m, res = [];
while (m = regex.exec(str)) {
res.push(m[1]);
}
console.log(res);

Get the string between the last 2 / in regex in javascript

How can I get the strings between last 2 slashes in regex in javascript?
for example:
stackoverflow.com/questions/ask/index.html => "ask"
http://regexr.com/foo.html?q=bar => "regexr.com"
https://www.w3schools.com/icons/default.asp => "icons"
You can use /\/([^/]+)\/[^/]*$/; [^/]*$ matches everything after the last slash, \/([^/]+)\/ matches the last two slashes, then you can capture what is in between and extract it:
var samples = ["stackoverflow.com/questions/ask/index.html",
"http://regexr.com/foo.html?q=bar",
"https://www.w3schools.com/icons/default.asp"]
console.log(
samples.map(s => s.match(/\/([^/]+)\/[^/]*$/)[1])
)
You can solve this by using split().
let a = 'stackoverflow.com/questions/ask/index.html';
let b = 'http://regexr.com/foo.html?q=bar';
let c = 'https://www.w3schools.com/icons/default.asp';
a = a.split('/')
b = b.split('/')
c = c.split('/')
indexing after split()
console.log(a[a.length-2])
console.log(b[b.length-2])
console.log(c[c.length-2])
I personally do not recommend using regex. Because it is hard to maintain
I believe that will do:
[^\/]+(?=\/[^\/]*$)
[^\/]+ This matches all chars other than /. Putting this (?=\/[^\/]*$) in the sequence looks for the pattern that comes before the last /.
var urls = [
"stackoverflow.com/questions/ask/index.html",
"http://regexr.com/foo.html?q=bar",
"https://www.w3schools.com/icons/default.asp"
];
urls.forEach(url => console.log(url.match(/[^\/]+(?=\/[^\/]*$)/)[0]));
You can use (?=[^/]*\/[^/]*$)(.*?)(?=\/[^/]*$). You can test it here: https://www.regexpal.com/
The format of the regex is: (positive lookahead for second last slash)(.*?)(positive lookahead for last slash).
The (.*?) is a lazy match for what's between the slashes.
references:
Replace second to last "/" character in URL with a '#'
RegEx that will match the last occurrence of dot in a string

Categories