Match strings using asterisks (wildcards) [duplicate] - javascript

This question already has answers here:
Wildcard string comparison in Javascript
(10 answers)
Closed 4 years ago.
I want to test if any string in an array matchs with a particular string. However, the strings in array may contain the asterisks pattern.
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*foo"];
var toMatch = "foo_1";
For this sample, the result will be true because foo_*, *foo_1 and foo_1* will match with foo_1, but bar and *foo won't.
I have tried to use split function with lodash _.some but it seems overcomplicated and I can't make it works consistently.
function isMatching() {
return _.some(toTest , function(a) {
return _.some(a.split("*"), function(part1, idx1) {
return (part1.length && _.some(toMatch.split(part1), function(part2, idx2) {
return (part2.length && idx1 == idx2);
}));
});
});
}

To achieve expected result, use below option of using filter, indexOf and replace
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*_foo"];
var toMatch = "foo_1";
console.log(toTest.filter(v => toMatch.indexOf(v.replace('*', '')) !== -1))

Related

Confused why my regex expression isn't working? [duplicate]

This question already has answers here:
Alternation operator inside square brackets does not work
(2 answers)
What's the difference between () and [] in regular expression patterns?
(6 answers)
Closed 3 years ago.
Attempting to create a regex expression that splits a string at ',' and '\n' and then a passed in custom delimiter (which is signified by firstChar in my code).
Format for the string being passed in: {delimiter}\n{numbers}. I've used regex101 online and it seems to work on there but in my actual code it doesn't split at the custom delimiter so not sure what I'm doing wrong.
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
strArr = str.split(/,|\n/) ;
} else {
strArr = str.split(/[,|\n|firstChar]/);
}
}
expect ';\n2;5' to equal 7 but my array splits into [";", "2;5"] for some reason.
Your first character isn't a number so you go to else condition directly, if you want a dynamic regex then you need to build it using RegExp
Also you don't need character class here
/[,|\n|firstChar]/
it should be
/,|\n|firstChar/
let splitter = (str) => {
if (str.includes('\n')) {
let firstChar = str.slice(0, 1);
if (parseInt(firstChar)) {
return str.split(/,|\n/);
} else {
let regex = new RegExp(`,|\\n|\\${firstChar}`, 'g') // building a dynamic regex here
return str.split(regex).filter(Boolean)
}
}
}
console.log(splitter(";\n2;5"))
console.log(splitter("*\n2*5"))

Finding ALL positions of a string within another string [duplicate]

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
JS Match all occurrences of substring in a string
(2 answers)
Closed 3 years ago.
I can't find out a solution to the following problem and it's driving me nuts. I need to find every position of a string within another string.
This is what I have come up with:
function getMatchIndices(regex, str) {
let result = [];
let match;
let regex = new RegExp(regex, 'g');
while (match = regex.exec(str))
result.push(match.index);
return result;
}
const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';
const indices = getMatchIndices(new RegExp(rule, "g"), line);
console.log(indices);
Now, the issue is that this does NOT match aba's that are formed in the middle of two other matches...
Here is an image illustrating the problem:
Any ideas?
I realize this is NOT a Regex solution. So it might not be what you need.
Hope it helps.
function getMatchIndices(r, str) {
const indices = [];
str.split('').forEach((v,i) => {
if(r === str.substring(i,i+r.length)) {
indices.push(i);
}
});
return indices;
}
const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';
const indices = getMatchIndices(rule, line);
console.log(indices);

How can I create an array including all matches of a regex in JavaScript? [duplicate]

This question already has an answer here:
Put all regex matches in an array?
(1 answer)
Closed 6 years ago.
I have this function which is supposed to put all matches regex returns when executed against a string str into the array res and then return it:
function matchAll(str, regex) {
var res = [];
var m;
while (m = regex.exec(str)) {
res.push(m[0]);
}
return res;
}
It creates an infinite loop with the regex /^\d\d*/i. Why?
Try this regex: \d\s[A-Z0-9]{3,3}
RegexPal (working solution): http://www.regexpal.com/?fam=96072

Get duplicate characters count in a string [duplicate]

This question already has answers here:
Counting frequency of characters in a string using JavaScript [duplicate]
(21 answers)
Closed 7 years ago.
Can anyone help me to get the count of repeated characters in a given string in javascript.
For example,
"abccdef" -> 1 (Only "c" repeated)
"Indivisibilities" -> 2 ("i" and "s" repeated)
Thank You
You can use like this
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
getFrequency('Indivisibilities');
This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.
We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join.
We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.
When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.
function howManyRepeated(str){
try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2

RegEx extract all real numbers from a string [duplicate]

This question already has answers here:
Regex exec only returning first match [duplicate]
(3 answers)
Closed 8 years ago.
This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?
/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")
returns:
["-8.075090"]
Try this code:
var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
alert(match);
}
Demo
http://jsfiddle.net/kCm4z/
Discussion
The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.
Alternatively, the regex can be written like this:
/[-+]?\d*\.?\d+/g
String.prototype.match gives you all matches:
var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"
console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]

Categories