regex search term in variable - regex

Do you know how I am able to put the search string inside the RegExp?
Let say if my search term is 'Ame', then I can write
v.name.search(new RegExp(/Ame/i)). //It works
var search = $("#search-query").val();
v.name.search(new RegExp('/'+search+'/i' //It doesn't work
However if the value 'Ame' was stored in the var 'search', how do I use the var?
var search = $("#search-query").val();
if($("#search-query").val().length <1){
$scope.hiddenError = true;
return;
}
$.each(json.products, function(i, v) {
if (v.name.search(new RegExp('/'+search+'/i')) != -1) { //doesn't work
$scope.recentGame.push({ label:v.name, value: v.type, link: v.url });
return;
}
});

When you want to build a custom regular expression from a string, you don't include the delimiters / or the options. You use the following form of the function constructor:
var regex = new RegExp(search, "i");
and use that in the search method.

Related

Typescript regex exclude whole string if followed by specific string

I'm been running into weird issues with regex and Typescript in which I'm trying to have my expression replace the value of test minus the first instance if followed by test. In other words, replace the first two lines that have test but for the third line below, replace only the second value of test.
[test]
[test].[db]
[test].[test]
Where it should look like:
[newvalue]
[newvalue].[db]
[test].[newvalue]
I've come up with lots of variations but this is the one that I thought was simple enough to solve it and regex101 can confirm this works:
\[(\w+)\](?!\.\[test\])
But when using Typescript (custom task in VSTS build), it actually replaces the values like this:
[newvalue]
[newvalue].[db]
[newvalue].[test]
Update: It looks like a regex like (test)(?!.test) breaks when changing the use cases removing the square brackets, which makes me think this might be somewhere in the code. Could the problem be with the index that the value is replaced at?
Some of the code in Typescript that is calling this:
var filePattern = tl.getInput("filePattern", true);
var tokenRegex = tl.getInput("tokenRegex", true);
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.info(`Starting regex replacement in [${file}]`);
var contents = fs.readFileSync(file).toString();
var reg = new RegExp(tokenRegex, "g");
// loop through each match
var match: RegExpExecArray;
// keep a separate var for the contents so that the regex index doesn't get messed up
// by replacing items underneath it
var newContents = contents;
while((match = reg.exec(contents)) !== null) {
var vName = match[1];
// find the variable value in the environment
var vValue = tl.getVariable(vName);
if (typeof vValue === 'undefined') {
tl.warning(`Token [${vName}] does not have an environment value`);
} else {
newContents = newContents.replace(match[0], vValue);
console.info(`Replaced token [${vName }]`);
}
}
}
Full code is for the task I'm using this with: https://github.com/colindembovsky/cols-agent-tasks/blob/master/Tasks/ReplaceTokens/replaceTokens.ts
For me this regex is working like you are expecting:
\[(test)\](?!\.\[test\])
with a Typescript code like that
myString.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
Instead, the regex you are using should replace also the [db] part.
I've tried with this code:
class Greeter {
myString1: string;
myString2: string;
myString3: string;
greeting: string;
constructor(str1: string, str2: string, str3: string) {
this.myString1 = str1.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
this.myString2 = str2.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
this.myString3 = str3.replace(/\[(test)\](?!\.\[test\])/g, "[newvalue]");
this.greeting = this.myString1 + "\n" + this.myString2 + "\n" + this.myString3;
}
greet() {
return "Hello, these are your replacements:\n" + this.greeting;
}
}
let greeter = new Greeter("[test]", "[test].[db]", "[test].[test]");
let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.greet());
}
document.body.appendChild(button);
Online playground here.

phrase search in meteor search-source package

I have a meteor app for which I added the search-source package to search certain collections and it works partially. That is, when I search for the term foo bar it returns results for each of "foo" and "bar". This is fine, but I want to also be able to wrap the terms in quotes this way: "foo bar" and get results for an exact match only. at the moment when i do this i get an empty set. Here is my server code:
//Server.js
SearchSource.defineSource('FruitBasket', function(searchText, options) {
// options = options || {}; // to be sure that options is at least an empty object
if(searchText) {
var regExp = buildRegExp(searchText);
var selector = {$or: [
{'fruit.name': regExp},
{'fruit.season': regExp},
{'fruit.treeType': regExp}
]};
return Basket.find(selector, options).fetch();
} else {
return Basket.find({}, options).fetch();
}
});
function buildRegExp(searchText) {
// this is a dumb implementation
var parts = searchText.trim().split(/[ \-\:]+/);
return new RegExp("(" + parts.join('|') + ")", "ig");
}
and my client code:
//Client.js
Template.dispResults.helpers({
getPackages_fruit: function() {
return PackageSearch_fruit.getData({
transform: function(matchText, regExp) {
return matchText.replace(regExp, "<b>$&</b>")
},
sort: {isoScore: -1}
});
}
});
Thanks in advance!
I've modified the .split pattern so that it ignores everything between double quotes.
/[ \-\:]+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/
Thus, you can simply wrap an exact phrase search in double quotes and it won't get split.
There is one more thing; since we don't need the quotes, they are removed in the next line using a .map function with a regex that replaces double quotes at the start or the end of a string part: /^"|"$/
Sample code:
function buildRegExp(searchText) {
// exact phrase search in double quotes won't get split
var arr = searchText.trim().split(/[ \-\:]+(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/);
var parts = arr.map(function(x){return x.replace(/^"|"$/g, '');});
return new RegExp("(" + parts.join('|') + ")", "ig");
}
console.log(buildRegExp("foo bar"));
console.log(buildRegExp("\"foo bar\""));

Extract string using regex in stored procedure

I have a regex expression in javascript which works fine.
var re = /^([0-9]?[A-Z]+?)\s*(?:FM)?[FGHJKMNQUVXZ](?:[02]0)?[12]?[0-9]/i;
var str = 'RVBM2016';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Now I am trying to reuse the same expression in my stored procedure in postgres. Here is how I am trying it:
select regexp_replace('BLM2016',
E'/^([0-9]?[A-Z]+?)\s*(?:FM)?[FGHJKMNQUVXZ](?:[02]0)?[12]?[0-9]/i', '', 'g')
This should return BL only. For RVBM2016 it should return RVB and so on..
But now it has no effect on the input text. Is there any syntactical mistake?
I was using the wrong method to extract string out of expression. The correct version is as follows if anyone is interested:
select (regexp_matches('BLM2016', '([0-9]?[A-Z]+?)\s*(?:FM)?[FGHJKMNQUVXZ](?:[02]0)?[12]?[0-9]', 'gi'))[1]

get the first parameter of a string using regular expression

function getParameterByName(name, str) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(str);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
I'm using this algorithm for getting the value from the string, found it in internet
my string is
mihpayid=403993715510554486&mode=CC&status=success&unmappedstatus=captured&key=JBZaLc&txnid=t39SfgBZFEFLwhxEC&amount=1000.0&addedon=2014-12-06+17%3A34%3A26&productinfo=Devthon&firstname=sasi.kanth80%40gmail.c&lastname=&address1=&address2=&city=&state=&country=&zipcode=&email=sasi.kanth80%40gmail.com
I'm able to get all the parameters like status key
But I'm unable to get the mihpayid value which is the first parameter
How can I get that any suggestion?
getParameterByName("success", data);
You can make use of this function which will form a flattened array looking like
[key,value, anotherkey,anothervalue,...] so we could just find the value by adding one to the index of key.
function getParameterByName(name, str) {
var arr = str.split('&').map(function(s){
return s.split('=')
}).join().split(","); // flatten the array
return decodeURIComponent(arr[arr.indexOf(name) + 1]);
}
A regular expression like /([a-zA-Z0-9]*)=([^&]*)/ig will return all matches with the variable and value conveniently sorted.
I think your solution is really close, it's just missing a couple of things. One not sure if it is a typo or not but the line var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); ends in a comma. Outside of this the only thing you needed to do is update the following [\\?&] to [\\?&]?
function getParameterByName(name, str) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]?" + name + "=([^&#]*)");
results = regex.exec(str);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
data="mihpayid=403993715510554486&mode=CC&status=success&unmappedstatus=captured&key=JBZaLc&txnid=t39SfgBZFEFLwhxEC&amount=1000.0&addedon=2014-12-06+17%3A34%3A26&productinfo=Devthon&firstname=sasi.kanth80%40gmail.c&lastname=&address1=&address2=&city=&state=&country=&zipcode=&email=sasi.kanth80%40gmail.com";
console.clear();
console.log(getParameterByName("unmappedstatus", data));
console.log(getParameterByName("status", data));
console.log(getParameterByName("mihpayid", data));
Results in Console:
regex:10 Console was cleared
regex:11 captured
regex:12 success
regex:13 403993715510554486
regex:1 undefined

AS3 RegEx returns null

Can anyone explain why the code below traces null when on the timeline?
var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\b|\/)/;
var str:String = "/num83r5/and/letters/4/A/";
trace(str.match(cleanRegExp.toString()));
I've read the documentation, so I'm pretty sure that I'm declaring the RegEx correctly and that String.match() should only return null when no pattern is passed in, otherwise it should be an array with 0+ elements. I suspected a badly written expression, but surely that should still return an empty array?
EDIT: Both these trace "no matches" instead of either 5 or 0, depending on the expression being correct:
var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\b|\/)/;
var str:String = "/num83r5/and/letters/4/A/";
var res:Array = str.match(cleanRegExp);
trace((res == null) ? "no matches" : res.length);
And:
var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\b|\/)/;
var str:String = "/num83r5/and/letters/4/A/";
var res:Object = cleanRegExp.exec(str);
trace((res == null) ? "no matches" : res[0]);
UPDATE
If you're going to work in flash with regex, this tool is a must-have:
http://gskinner.com/RegExr/
http://gskinner.com/RegExr/desktop/
ORIGINAL ANSWER
Don't use toString(), you're then doing a literal search, which will include the addition of all of your regex formatting, including flags. Do:
str.match(cleanRegExp);
In fact the proper method is to reference the returned object like so:
var results:Array = str.match(cleanRegExp);
if(results != null){
//We have a match!
}