how to check if a string matches a pattern with asterisk - javascript

I have a list of files:
var files = [
"user_parse_info",
"user_parse_age",
"site_render_info",
"site_parse_name"
]
Now I have string a pattern:
var pattern = "site_*_name";
This should match only the last file.
How can I check this? Maybe an RegExp?

Yes, regular expression would be a better choice for this.
var _ = require('nimble');
var files = [
"user_parse_info",
"user_parse_age",
"site_render_info",
"site_parse_name"
];
var re = /^site_.*_name$/;
var result = _.filter(files, function (val) {
return re.test(val);
});

Using a regular expression means that you would need to escape some characters like . and $, otherwise they can give false positives or keep the pattern from matching anything.
You can just split the string on the asterisk and check the parts against the string:
var parts = pattern.split('*');
if (
str.length >= parts[0].length + parts[1].length &&
str.substr(0, parts[0].length) == parts[0] &&
str.substr(str.length - parts[1].length) == parts[1])
{
// matches
}
Demo: http://jsfiddle.net/Guffa/u8XEE/

Related

JavaScript Split with RegEx without Global Match

I have an expression.
var expression = "Q101='You will have an answer here like a string for instance.'"
I have a regular expression that searches the expression.
var regEx = new regExp(/=|<>|like/)
I want to split the expression using the regular expression.
var result = expression.split(regExp)
This will return the following:
["Q101", "'You will have an answer here ", " a string for instance'"]
This is not what I want.
I should have:
["Q101", "'You will have an answer here like a string for instance'"]
How do I use the regular expression above to split only on the first match?
Since you only want to grab the two parts either side of the first delimiter it might be easier to use String.match and discard the whole match:
var expression = "Q101='You will have an answer here like a string for instance.'";
var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
JavaScript's split method won't quite do what you want, because it will either split on all matches, or stop after N matches. You need an extra step to find the first match, then split once by the first match using a custom function:
function splitMatch(string, match) {
var splitString = match[0];
var result = [
expression.slice(0, match.index),
expression.slice(match.index + splitString.length)
];
return result;
}
var expression = "Q101='You will have an answer here like a string for instance.'"
var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)
if (match) {
var result = splitMatch(expression, match);
console.log(result);
}
While JavaScript's split method does have an optional limit parameter, it simply discards the parts of the result that make it too long (unlike, e.g. Python's split). To do this in JS, you'll need to split it manually, considering the length of the match —
const exp = "Q101='You will have an answer here like a string for instance.'"
const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]
const result = splitPos != -1 ? (
[
exp.substring(0, splitPos),
exp.substring(splitPos + splitStr.length),
]
) : (
null
);
console.log(result)

JavaScript RegExp - find all prefixes up to a certain character

I have a string which is composed of terms separated by slashes ('/'), for example:
ab/c/def
I want to find all the prefixes of this string up to an occurrence of a slash or end of string, i.e. for the above example I expect to get:
ab
ab/c
ab/c/def
I've tried a regex like this: /^(.*)[\/$]/, but it returns a single match - ab/c/ with the parenthesized result ab/c, accordingly.
EDIT :
I know this can be done quite easily using split, I am looking specifically for a solution using RegExp.
NO, you can't do that with a pure regex.
Why? Because you need substrings starting at one and the same location in the string, while regex matches non-overlapping chunks of text and then advances its index to search for another match.
OK, what about capturing groups? They are only helpful if you know how many /-separated chunks you have in the input string. You could then use
var s = 'ab/c/def'; // There are exact 3 parts
console.log(/^(([^\/]+)\/[^\/]+)\/[^\/]+$/.exec(s));
// => [ "ab/c/def", "ab/c", "ab" ]
However, it is unlikely you know that many details about your input string.
You may use the following code rather than a regex:
var s = 'ab/c/def';
var chunks = s.split('/');
var res = [];
for(var i=0;i<chunks.length;i++) {
res.length > 0 ? res.push(chunks.slice(0,i).join('/')+'/'+chunks[i]) : res.push(chunks[i]);
}
console.log(res);
First, you can split the string with /. Then, iterate through the elements and build the res array.
I do not think a regular expression is what you are after. A simple split and loop over the array can give you the result.
var str = "ab/c/def";
var result = str.split("/").reduce(function(a,s,i){
var last = a[i-1] ? a[i-1] + "/" : "";
a.push(last + s);
return a;
}, []);
console.log(result);
or another way
var str = "ab/c/def",
result = [],
parts=str.split("/");
while(parts.length){
console.log(parts);
result.unshift(parts.join("/"));
parts.pop();
}
console.log(result);
Plenty of other ways to do it.
You can't do it with a RegEx in javascript but you can split parts and join them respectively together:
var array = "ab/c/def".split('/'), newArray = [], key = 0;
while (value = array[key++]) {
newArray.push(key == 1 ? value : newArray[newArray.length - 1] + "/" + value)
}
console.log(newArray);
May be like this
var str = "ab/c/def",
result = str.match(/.+?(?=\/|$)/g)
.map((e,i,a) => a[i-1] ? a[i] = a[i-1] + e : e);
console.log(result);
Couldn't you just split the string on the separator character?
var result = 'ab/c/def'.split(/\//g);

How to split a string at commas but ignore \,?

I want to split string http://some.com/\,brabra,400,500 into ['http://some.com/\,brabra', 400, 500]
I already tried this, but error because lookbehind is not support in js.
'http://some.com/\,brabra,400,500'.split(/(?<!\\),/g)
Any other ideas to do this?
You may use matching approach with (?:[^,\\]+|\\.)+:
match(/(?:[^,\\]+|\\.)+/g)
See the regex demo
Details: the (?:[^,\\]+|\\.)+ matches 1 or more occurrences ((?:...)+) of a 1+ characters other than , and \ (with [^,\\]+) or (|) any escaped sequence (\\.)
var s = "http://some.com/\\,brabra,400,500"
console.log(s.match(/(?:[^,\\]+|\\.)+/g));
Or a workaround if the comma to be split with is always followed with a digit:
split(/,(?=\d)/)
See this regex demo
var s = "http://some.com/\\,brabra,400,500"
console.log(s.split(/,(?=\d)/));
A classic, if slightly inelegant approach for such problems is to replace some characters with a magic token, then put them back later:
str
.replace("\\,", "DONT_SPLIT_HERE")
.split(',')
.map(part => part.replace("DONT_SPLIT_HERE", "\\,")
you can use simulate positive lookaheads with reversing the string:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
Array.prototype.reverseElements = function() {
var ar = [];
for (var i = 0; i < this.length; i++) {
if (typeof this[i] === 'string')
ar[i] = this[i].reverse();
else {
//Do something if not a String
}
}
return ar;
}
var str = "http://some.com/\,brabra,400,500";
var ar = str.reverse().split(/,(?!\\)/).reverse().reverseElements();
console.log(ar);
Note: The Regex works here, but not in the snippet.

Test if all given char's are in string - Javascript

I'm looking for smart, fast and simple way to check if the string contains all of the predefined char's.
For example:
var required = 'cfov'; //These are the char's to test for.
var obj = {valid: 'vvcdfghoco'}; //Valid prop can contains any string.
//what I have so far::
var valid = obj.valid, i = 0;
for(; i < 4; i++) {
if(valid.indexOf(required.chatAt(i)) === -1) {
break;
}
}
if(i !== 3) {
alert('Invalid');
}
Can we do it in RegExp? if yes, any help plz!
Thanks in Advance.
You can build a lookahead regex for your search string:
var re = new RegExp(required.split('').map(function(a) {
return "(?=.*" + a + ")"; }).join(''));
//=> /(?=.*c)(?=.*f)(?=.*o)(?=.*v)/
As you note that this regex is adding a lookahead for each character in search string to make sure that all the individual chars are present in the subject.
Now test it:
re.test('vvcdfghoco')
true
re.test('vvcdghoco')
false
re.test('cdfghoco')
false
re.test('cdfghovco')
true
You can do this way:
var required = 'cfov'; //These are the char's to test for.
var valid = 'vvcdfghoco'; //Valid prop can contains any string.
var regex = new RegExp("^[" + valid + "]*$");
/* this line means:
from start ^ till * the end $ only the valid characters present in the class [] */
if (required.match(regex)) {
document.write('Valid');
}
else {
document.write('Invalid');
}
Hope it helps.

JavaScript RegExp: Different results: Built pattern using string & using regexp "literal"?

Is there any differences between using RegExp literals vs strings?
http://jsfiddle.net/yMMrk/
String.prototype.lastIndexOf = function(pattern) {
pattern = pattern + "(?![\s\S]*" + pattern + ")";
var match = this.match(pattern);
return (match == null) ? -1 : match.index;
}
function indexOfLastNewline(str) {
var match = str.match(/\r?\n(?![\s\S]*(\r?\n))/);
return (match == null) ? -1 : match.index;
}
var str = "Hello 1\nHello 2\nHello 3\nHello4";
alert(str.lastIndexOf("(\r?\n)")); // always returns the 1st newline (7)
alert(indexOfLastNewline(str)); // returns correctly (23)
Update
even if I use a RegExp object, I still get the same result
http://jsfiddle.net/yMMrk/2/
You need to escape your \ in the string version as \\, like this:
String.prototype.lastIndexOf = function(pattern) {
pattern = pattern + "(?![\\s\\S]*" + pattern + ")";
var match = this.match(pattern);
return (match == null) ? -1 : match.index;
}
function indexOfLastNewline(str) {
var match = str.match(/\r?\n(?![\s\S]*(\r?\n))/);
return (match == null) ? -1 : match.index;
}
var str = "Hello 1\nHello 2\nHello 3\nHello4";
alert(str.lastIndexOf("(\\r?\\n)")); // returns correctly (23)
alert(indexOfLastNewline(str)); // returns correctly (23)
You can test it out here.
Generally speaking, if you use a string to construct a regex, you need to escape backslashes; if you use a regex literal, you need to escape slashes if they occur in your regex.
So the regex
\s/
can be written as a JavaScript string like this:
"\\s/"
and as a JavaScript regex literal like this:
/\s\//
Also, there is a difference in the handling of mode modifiers. For example, to make a regex case-insensitive, you can construct a regex object from a JavaScript string like this:
var myre = new RegExp("[a-z]", "i");
With a regex literal, you can do that directly:
var myre = /[a-z]/i;
Also, see this tutorial.

Categories

Resources