RegEx match not working - javascript

So what I want to match is anything that ends with ".ProjectName" so I wrote a small test case. I purposely created the pattern using RegExp because in the real case scenario I will be using a variable as part of the reg ex pattern. I'm not sure if my pattern is not correct (90% sure it correct), or if I am misusing the match function (70% sure I am suing it right). The blow code returns me something when the second case notMatchName should not return me anything
var inputName = "ProjectName";
var matchName = "userInput_Heading.Heading.ProjectName";
var notMatchName = "userInput_Heading.Heading.Date";
var reg = new RegExp(".*[." + inputName + "]");
console.log(reg);
console.log(matchName.match(reg));
console.log(matchName.match(reg)[0]);
console.log(notMatchName.match(reg));
console.log(notMatchName.match(reg)[0]);
Here is the JsFiddle to help.

Use
var reg = new RegExp(".*\." + inputName);
The square brackets mean: one character, which is one of those within the brackets. But you want several characzters, first a dot, then the first character of inputName, etc.

your regular expression should be .*\.projectName
if you rewrite your statement it will be
var reg = new RegExp(".*\." + inputName)

Related

Javascript RegEx for Pattern Not Working

This should be easy. I have the following code:
var patt = new RegExp("\d{3}[\-]\d{1}");
var res = patt.test(myelink_account_val);
if(!res){
alert("Inputs must begin with something like XXX-X of numbers and a dash!");
return;
}
Basically, forcing users to enter something like 101-4 . The code is borrowed from Social Security Number input validation . And I can confirm that my inputs are indeed like 101-4; only the first five characters need to fit the pattern.
But running my code always gives the alert--the condition is never matched.
Must be something simple?!
Thanks.
When you use "new RegExp" you are passing it a string.
Two solutions here:
1) Don't use "new RegExp()", but a regexp pattern:
var patt = /\d{3}[\-]\d{1}/
2) If you want to use it, remember you will have to escape the escapes:
var patt = new RegExp("\\d{3}[\\-]\\d{1}");
Also, remember, if a '-' is the only symbol (or first, or last) on a [], you can skip the escape:
var patt = new RegExp("\\d{3}[-]\\d{1}");
var patt = new RegExp("^\\d{3}[\\-]\\d{1}");
console.log(patt.test("123-4"));
console.log(patt.test("123-456"));
console.log(patt.test("12-4"));
console.log(patt.test("abc-d"));

Regular Expression (string compare)

I have written this in javascript (web) but since i try to use RegExpression it should work almost the same.
I have a string with some coordinates in it seperated by a space charakter.
var coords = "0:0 0:0:0 1:0:1 0:0:0:1";
var part = "0:0";
I want to have all the coordinates beginning with the value of part ("0:0");
What I tryed is something like:
var reg = new RegExp(part+"*");
alert(coords .match(reg));
But it seems not to work propperly.
It should match "0:0" and "0:0:0" and "0:0:0:1" but NOT "1:0:1" (edit)
Anyone has an idea?!
Kind regards!
You should use this regex:
var reg = new RegExp("(^|\\s)(" + part + "\\S*)", "g");
that is to match all non-space characters after 0:0 and stop when it hits a space or line end.

Finding image url via using Regex

Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

Javascript Regexp Duplicate Line Matching not working correctly

I am writing a Javascript code to parse some grammar files, it is quite some code but I will post relevant information here. I am using Javascript Regexp in order to match a duplicate line held within a string. The string contains, for example (assume the string name is lines):
if
else
;
print
{
}
test1
test1
=
+
-
*
/
(
)
num
string
comment
id
test2
test2
What should happen, is a match found on 'test1' and 'test2'. It should then delete the duplicate, leaving 1 instance of test1 and test2. What is happening is no match at all. I am confident in my regex but javascript may be doing something I am not expecting. Here is the code doing the work on the string given above:
var rex = new RegExp("(.*)(\r?\n\1)+","g");
var re = '/(.*)(\r?\n\1)+/g';
rex.lastIndex = 0;
var m = rex.exec(lines);
if (m) {
alert("Found Duplicate");
var linenum = lines.search(re); //Get line number of error
alert("Error: Symbol Defined twice\n");
alert("Error occured on line: " + linenum);
lines = lines.replace(rex,""); //Gets rid of the duplicate
}
It never gets into the if(m) statement. Therefore no match is found. I tested the regex here: http://regexpal.com/ using the regex in my code as well as the example text provided. It matches just fine, so I am at kind of a loss. If anyone can help, it would be great.
Thank you.
Edit:
Forgot to add, I am testing this in firefox, and it only has to work in firefox. Not sure if that matters.
First error: \ in a JS string is also an escape character.
var rex = new RegExp("(.*)(\r?\n\1)+","g");
should be written
var rex = new RegExp("(.*)(\\r?\\n\\1)+","g");
// or, shorter:
var rex = /(.*)(\r?\n\1)+/g;
if you want to make it work. In the case of the RegExp constructor, you’re passing the pattern as a string to the constructor function. This means you need to escape each \ backslash that occurs in the pattern. If you use a regexp literal, you don’t need to escape them, since they’re not in a string, but retain their ‘normal’ properties in the regexp pattern.
Second error, your expression
var re = '/(.*)(\r?\n\1)+/g';
is wrong. What you’re doing here is assigning a string literal to a variable. I’m assuming you meant to assign a regular expression literal, which should be written like this:
var re = /(.*)(\r?\n\1)+/g;
Third error: the last line
lines = lines.replace(rex,""); //Gets rid of the duplicate
removes both instances of all duplicate lines! If you want to keep the first instance of each duplicate, you should use
lines = lines.replace(rex, "$1");
And finally, this method only detects two consecutive identical lines. Is that what you want, or do you need to detect any duplicates, wherever they may be?
var str = 'if\nelse\n;\nprint\n{\n}\ntest1\ntest1\n=\n+\n-\n*\n/\n(\n)\nnum\nstring\ncomment\nid\ntest2\ntest2\ntest2\ntest2\ntest2';
console.log(str);
str = str.replace(/\r\n?/g,'');
// I prefer replacing all the newline characters with \n's here
str = str.replace(/(^|\n)([^\n]*)(\n\2)+/g,function(m0,m1,m2,m3,ind) {
var line = str.substr(0,ind).split(/\n/).length + 1;
var msg = '[Found duplicate]';
msg += '\nFollowing symbol defined more than once';
msg += '\n\tsymbol: ' + m2;
msg += '\n\ton line ' + line;
console.log(msg);
return m1 + m2;
});
console.log(str);
Otherwise you can skip the first line and change the pattern into
/(^|\r\n?|\n)([^\r\n]*)((?:\r\n?|\n)\2)+/g
Note that [^\n]* will also catch multiple empty lines. If you want to make sure it matches (and replaces) non-empty lines then you might want to use [^\n]+.
[EDIT]
For the record, each m represents each arguments object, so m0 is the whole match, m1 is the 1st subgroup ((^|\n)), m2 is the 2nd subgroup (([^\n]*)) and m3 is the last subgroup ((\n\2)). I could have used arguments[n] instead but these are shorter.
As with the return value, due to lack of lookbehind in the regex flavor used by Javascript, this pattern is catching a possible preceding newline (unless it is the first line) so it needs to return the match and that preceding newline if any. That's why it shouldn't be returning m2 only.

Javascript Complex RegEx with variables

I am using this tool to build a regex http://www.gethifi.com/tools/regex
I found that the one below works for me if, for example, I am looking to match $aazz[AB]:
var regex = /[\+\=\-\*\^\\]\$aazz\[AB\]/g;
I have read the other posts on the RegEx constructor in Javascript but cannot manage to make the following work:
var preToken = "[\+\=\-\*\^\\]";
var toFind = "\$aazz\[AB\]";
var stringToReplace = "/" + preToken + toFind + "/";
var regex = new RegExp(stringToReplace, "g");
Here is the jsbin http://jsbin.com/ifeday/3/edit
Thanks
When creating regular expressions from strings, you need to escape your backslashes twice.
\ becomes \\
\\ becomes \\\\
So, you can try (in a character class not everything needs escaping):
var preToken = "[+=\\-*^\\\\]";
var toFind = "azz\\[A\\]";
Also, the string source for your regular expression does not need to be bound by /s, but I see in your jsBin that you've already corrected that.
Update your jsBin with these variable declarations, it should work now.

Categories