AS3 RegEx returns null - regex

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!
}

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.

regex search term in variable

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.

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

flex match regex

I have asked this question before and got some reponses but i am still not cleared on how to do this, if someone could help me more i would appreciate.
What i am doing is reading some information from a URL then i am using a regex(match) to get the string that i need. However i need the result for each match to be a string because i need to manipulate this string. below is the code tha t i have. Any help is appeciated.Again i have asked this but i am not sure how to proceed on my side.
var composer:StandardFlowComposer = txtSource.textFlow.flowComposer as StandardFlowComposer;
var pattern:RegExp= new RegExp("href=\"/player/.*?\">");
var pattern2:RegExp= new RegExp("href=\"/player/.*?\"");
var myArrayOfLines:Array = ul.data.split(/\n/);
var line:Array;
var str:String = "";
var lineFinal:Array;
var lineURL:String;
lineFinal = myArrayOfLines;
for each (var lineRaw:String in myArrayOfLines)
{
trace(lineRaw);
}
trace(line);
Anymore help is appreciated. thank you very much.
Try this , this will matches the specifed pattern against the string and returns array of strings...
var myArrayOfLines:Array = ul.data.match(/"your pattern here"/gs);
for each (var lineRaw:String in myArrayOfLines)
{
trace(lineRaw);
}
trace(line);
Try your regex here