How to convert regular expression to all possible cases? - javascript

convert a regular expression to all possible cases
For Example:
1.9856[1-4] then it should return values like 98561,98562,98563,98564
2.98[4-5]65 then it should return values 98465,98565

You can use the regex /\[(\d)-(\d)\]/ and match to get the start and end of the range. Then use a for loop to replace the match with numbers from start to end
function getCombinations(str) {
const regex = /\[(\d)-(\d)\]/,
[match, start, end] = str.match(regex),
output = []
for (let i = +start; i <= +end; i++)
output.push(str.replace(match, i))
return output
}
console.log(getCombinations('1.9856[1-4]'))
console.log(getCombinations('2.98[4-5]65'))
This works for only single range in the input string. For multiple ranges, you can use exec to get multiple matches and replace based on the index of the match

You can use Regex to match exact numbers or you can use \d to match any digits.
For your first example where 9856[1-4] then it should return values like 98561,98562,98563,98564,
you can return all numbers in a string that begin with 9856 and ends with any number ranging from 1-4 like so:
let nums = "985612, 985622, 985633, 985644, 985655"
let regex = /9856[1-4]/g
let result = nums.match(regex)
console.log(result)
For the second example where 98[4-5]65 then it should return values 98465, 98565
let nums = "98465, 98565"
let regex = /98[4-5]{2}65/g
let result = nums.match(regex)
console.log(result)

Related

Getting second digit in a string using Javascript + Regex?

I'm wondering how I can get the second digit of a string where we don't know the number of digits the second number will be and without using splice or substring.
Ex. Channel.0.This.13
Should Return: 13
I've seen a few similar questions but they
typically know the number of digits the second number will be or
use splicing and substring, which I do not want to use in this case.
I appreciate the help :)
You could use String.prototype.match
In case that the string does not have any number, which matches will return null, you should use optional chaining ?. for a safer array index access
const str = "Channel.0.This.13";
const res = str.match(/\d+/g)?.[1];
console.log(res);
Use this regex (\d*)$. This will return only group with numbers which in the end of the string.
try this:
^[^\d]*\d+[^\d]+(\d+).*
Example:
const secondDigit = "Channel.0.This.13".match(/^[^\d]*\d+[^\d]+(\d+).*/).pop();
console.log(Number(secondDigit)); // 13
Assuming the original string contains only alphabets, numbers and '.' (in between),
Here is my solution (Pseudo code):
String givenString;
regex=/([0-9]+)(\.[a-zA-Z]+)?(\.[0-9]+)/;
//below code will return an array or null (if no second number is present)
match=givenString.match(regex);
//access last element of array. It will be like '.13' , just remove '.' and you are good to go
match.pop()
Javascript Regex Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
String.prototype.match() returns an array whose contents depend on the presence or absence of the global (g) flag, or null
const input1 = "Channel.0.This.13",
input2 = "Channel.0.This",
input3 = "Channel.This.";
const digitMatch = function (input) {
const digits = input.match(/\d+/g);
return (digits && digits[1]) || "Not Found";
};
console.log(digitMatch(input1));
console.log(digitMatch(input2));
console.log(digitMatch(input3));
if no matches are found.
It will help .*?\d+.*?(\d+).*$
"Channel.0.This.13.Channel.0.This.56".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
"Channel.0.This.13".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
You can reference the regex .match() key. str.match(reg)[1]
const str1 = 'Channel.0.This.13'
const str2 = 'some.otherStrin8..'
const str3 = '65 people.For.&*=20.them,98'
const regex = /\d+/g
function matchSecond(str, reg) {
str.match(reg)[1] ? output = str.match(reg)[1] : output = false
return output;
}
console.log(matchSecond(str1,regex))
console.log(matchSecond(str2,regex))
console.log(matchSecond(str3,regex))

Javascript split by numbers using regex

I'm trying to come up with a regex that will do following.
I have a string
var input_string = "E100T10P200E3000T3S10";
var output=input_string.split(**Trying to find this**);
this should give an array with all the letters in order with repetitions
output = ["E","T","P","E","T","S"]
See below. \d+ means one or more digits; filter (x => x) removes empty strings that can appear in the beginning or the end of the array if the input string begins or ends with digits.
var input_string = "E100T10P200E3000T3S10";
var output = input_string.split (/\d+/).filter (x => x);
console.log (output);
We can try just matching for capital letters here:
var input_string = "E100T10P200E3000T3S10";
var output = input_string.match(/[A-Z]/g);
console.log(output);
Another approach is spread the string to array and use isNaN as filter callback
var input_string = "E100T10P200E3000T3S10";
var output = [...input_string].filter(isNaN);
console.log(output);
You can use regex replace method. First replace all the digits with empty string and then split the resultant string.
const input_string = 'E100T10P200E3000T3S10';
const ret = input_string.replace(/\d/g, '').split('');
console.log(ret);

Javascript get only matched text in regex

I have string like below
BANKNIFTY-13-FEB-2020-31200-ce
I want to convert the string to 13-FEB-31200-ce
so I tried below code
str.match(/(.*)-(?:.*)-(?:.*)-(.*)-(?:.*)-(?:.*)/g)
But its returning whole string
Two capture groups is probably the way to go. Now you have two options to use it. One is match which requires you to put the two pieces together
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.match(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/)
// just reference the two groups
console.log(`${match[1]}${match[2]}`)
// or you can remove the match and join the remaining
match.shift()
console.log(match.join(''))
Or just string replace which you do the concatenation of the two capture groups in one line.
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.replace(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/, '$1$2')
console.log(match)
Regex doesn't seem to be the most appropriate tool here. Why not use simple .split?
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.split('-');
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
If you really want to use regexp,
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.match(/[^-]+/g);
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
I would not use Regex at all if you know exact positions. Using regex is expensive and should be done differently if there is way. (https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/)
const strArr = "BANKNIFTY-13-FEB-2020-31200-ce".split("-"); // creates array
strArr.splice(0,1); // remove first item
strArr.splice(2,1); // remove 2020
const finalStr = strArr.join("-");
If the pattern doesn't need to be too specific.
Then just keep it simple and only capture what's needed.
Then glue the captured groups together.
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let m = str.match(/^\w+-(\d{1,2}-[A-Z]{3})-\d+-(.*)$/)
let result = m ? m[1]+'-'+m[2] : undefined;
console.log(result);
In this regex, ^ is the start of the string and $ the end of the string.
You can have something like this by capturing groups with regex:
const regex = /(\d{2}\-\w{3})(\-\d{4})(\-\d{5}\-\w{2})/
const text = "BANKNIFTY-13-FEB-2020-31200-ce"
const [, a, b, c] = text.match(regex);
console.log(`${a}${c}`)

matchAll Array for Group 1 Regex Matches

I'm trying to figure out a way to get all my Group 1 matches into an array without using a loop with matchAll().
Here's what I have thus far, but it only yields the first match:
let str = "123ABC, 123ABC"
let results = str.matchAll(/123(ABC)/gi);
let [group1] = results;
alert(group1[1]);
How can I get the results of the matchAll into one single array? Aka:
// ABC, ABC
const str = "123ABC, 123ABC"
const results = Array.from(
str.matchAll(/123(ABC)/gi),
([_, g1]) => g1
)
console.log(results)
If you only need the abc part of the string then you don't need to use matchAll method. You can easily get the results you want simply using the positive lookbehind regex expresion with the match method.
let str = "123ABC, 123ABC"
let results = str.match(/(?<=123)ABC/gi);
console.log(results)
// ["ABC","ABC"]
Here is some more information on these types of regex expressions Lookahead and lookbehind
You can use Array.from to convert results to array and perform map in one go:
const matches = Array.from(results, match => match[1])

How to process string so to keep characters up to last digit?

Given strings such as G08a, Professor3, Obs...
How to slice these strings after the last digit, so it returns :
G08a ==> G08
Professor3 ==> Professor3
Obs ==> Obs
Starting jsfiddle : https://jsfiddle.net/dpyqg2mk/
You can use a regex for this.
var ss = ["G08a", "Professor3", "Obs"];
var res = ss.map(s => (/^(.*?\d)\D*$/.exec(s) || [,s])[1]);
console.log(res);
This collects all characters up through a digit that is followed by a series of zero or more non-digits that continue to the end of the string. The initial characters and that last digit before the non-digits are captured in a group.
I used .map() as a convenience for the demo, and substituted a temporary array when the regex finds no match.
Short and simple:
let str = "foo9bar";
str = str.match(/(.*\d)|(.*\d?)/g)[0]; // str is now foo9
let elem = document.getElementById('txt');
elem.innerHTML = elem.innerHTML.match(/(.*\d)|(.*\d?)/g)[0];
<p id="txt">foo9bar</p>
First you need to find first digit' position in string
var str = "G08a";
var match = str.match(/(\D+)?\d/)
var index = match ? match[0].length-1 : -1;
Then make substring
var result =str.substring(0,index);
You could match the string by using a search for any character foolowd by a digit or any character which are followed ba a non digit or end of string.
console.log(['G08a', 'Professor3', 'Obs', 'abc123def456ghi'].map(function (s) {
return s.match(/^.*\d|.*(?=\D|$)/)[0];
}));

Categories

Resources