Brackets in Regular Expression - javascript

I'd like to compare 2 strings with each other, but I got a little problem with the Brackets.
The String I want to seek looks like this:
CAPPL:LOCAL.L_hk[1].vorlauftemp_soll
Quoting those to bracket is seemingly useless.
I tried it with this code
var regex = new RegExp("CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll","gi");
var value = "CAPPL:LOCAL.L_hk[1].vorlauftemp_soll";
regex.test(value);
Somebody who can help me??

It is useless because you're using string. You need to escape the backslashes as well:
var regex = new RegExp("CAPPL:LOCAL.L_hk\\[1\\].vorlauftemp_soll","gi");
Or use a regex literal:
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi
Unknown escape characters are ignored in JavaScript, so "\[" results in the same string as "[".

In value, you have (1) instead of [1]. So if you expect the regular expression to match and it doesn't, it because of that.
Another problem is that you're using "" in your expression. In order to write regular expression in JavaScript, use /.../g instead of "...".
You may also want to escape the dot in your expression. . means "any character that is not a line break". You, on the other hand, wants the dot to be matched literally: \..

You are generating a regular expression (in which [ is a special character that can be escaped with \) using a string (in which \ is a special character).
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi;

Related

why does this js RegExp test return true? [duplicate]

The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'
this is the expression
[\s\/\)\(\w&-]
I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?
var programProductRegex = new RegExp([\s\/\)\(\w&-]);
You can use the regular expression syntax:
var programProductRegex = /[\s\/\)\(\w&-]/;
You use forward slashes to delimit the regex pattern.
If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:
var programProductRegex = new RegExp("[\\s\\/\\)\\(\\w&-]");
All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.
Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.
var programProductRegex = new RegExp(userInput);
If you are using a String and want to escape characters like (, you need to write \\( (meaning writing backslash, then the opening parenthesis => escaping it).
If you are using the RegExp object, you only need one backslash for each character (like \()
Enclose your regex with delimiters:
var programProductRegex = /[\s\/)(\w&-]/;

Issue with custom javascript regex

I have a custom regular expression which I use to detect whole numbers, fractions and floats.
var regEx = new RegExp("^((^[1-9]|(0\.)|(\.))([0-9]+)?((\s|\.)[0-9]+(/[0-9])?)?)$");
var quantity = 'd';
var matched = quantity.match(regEx);
alert(matched);
​
(The code is also found here: http://jsfiddle.net/aNb3L/ .)
The problem is that for a single letter it matches, and I can't figure out why. But for more letters it fails(which is good).
Disclaimer: I am new to regular expressions, although in http://gskinner.com/RegExr/ it doesn't match a single letter
It's easier to use straight regular expression syntax:
var regEx = /^((^[1-9]|(0\.)|(\.))([0-9]+)?((\s|\.)[0-9]+(\/[0-9])?)?)$/;
When you use the RegExp constructor, you have to double-up on the backslashes. As it is, your code only has single backslashes, so the \. subexpressions are being treated as . — and that's how single non-digit characters are slipping through.
Thus yours would also work this way:
var regEx = new RegExp("^((^[1-9]|(0\\.)|(\\.))([0-9]+)?((\\s|\\.)[0-9]+(/[0-9])?)?)$");
This happens because the string syntax also uses backslash as a quoting mechanism. When your regular expression is first parsed as a string constant, those backslashes are stripped out if you don't double them. When the string is then passed to the regular expression parser, they're gone.
The only time you really need to use the RegExp constructor is when you're building up the regular expression dynamically or when it's delivered to your code via JSON or something.
Well, for a whole number this would be your regex:
/^(0|[1-9]\d*)$/
Then you have to account for the possibility of a float:
/^(0|[1-9]\d*)(.\d+)?$/
Then you have to account for the possibility of a fraction:
/^(0|[1-9]\d*)((.\d+)|(\/[1-9]\d*)?$/
To me this regex is much easier to read than your original, but it's up to you of course.

Different in Convert Regular Expression String to RegExp in Javascript

Why isn't my code around the test function in Object RegExp working the same way as the regex pattern. Am I missing something or Am I using the wrong escape regex
<html>
<body>
<script type="text/javascript">
var str = "info#test.com";
//This isn't working
var regStr = "^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$"; //This string can be any regex get from XSLT
//Escape function get from: http://stackoverflow.com/a/6969486/193850
regStr = regStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
console.log(regStr); // \^\(\[w\-\]\+\(\?:\.\[w\-\]\+\)\*\)#\(\(\?:\[w\-\]\+\.\)\*w\[w\-\]\{0,66\}\)\.\(\[a\-z\]\{2,6\}\(\?:\.\[a\-z\]\{2\}\)\?\)\$
var re = new RegExp(regStr , "i");
console.log(re.test(str)); //false
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
console.log(filter.test(str)); //true
</script>
</body>
</html>
You have to double your backslashes when you write a regular expression as a string.
Why? The string literal syntax also observes its own backslash-quoting convention, for things like quote characters, newlines, etc. Therefore, when JavaScript parses your string constant that contains the regular expression, the backslashes will disappear. Thus, you need to quote them with another backslash so that when you pass the string to the RegExp constructor it sees the regular expression you actually intended.
See, there's a confusion. The function you've used is a nice way of preprocessing your string-to-be regexes so you don't have to worry about escaping regex metacharacters - i.e., symbols that will control the regex behaviour, and not just taken literally.
But the point is that your string has already been parsed before it was taken by this escaping function: \w and \. sequences became just w and . respectively, the preceding slash was lost.
For characters not listed in Table 2.1, a preceding backslash is
ignored, but this usage is deprecated and should be avoided.
The escaper function, actually, did restore the slash before the ., but w wasn't special for it in any kind. ) Therefore the string that went into RegExp constructor had [w] instead of [\w].
It's actually quite easy to check: just console.log(regStr) after the replacement operation.

javascript: some problem with compiler interpreting // as comments in regex

I've got this regular expression for validating phone numbers
^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$
I dugged it out from my C#/vb library and now i want to translate it into javascript. But it has syntax error (i suspect it is something due to the // characters). my attempt:
$IsPhone = function (input) {
var regex = new window.RegExp("^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$", "");
return regex.test(input.trim());
};
alert($IsPhone("asd"));
Your problem has nothing to do with comments. You're just mixing up the two different ways of creating RegExp objects.
When you create a RegExp object in JavaScript code, you either write it as a string literal which you pass to a RegExp constructor, or as a regex literal. Because string literals support backslash-escape sequences like \n and \", any actual backslash in the string has to be escaped, too. So, whenever you need to escape a regex metacharacter like ( or +, you have to use two backslashes, like so:
var r0 = "^$|^(\\+?|(\\(\\+?[0-9]{1,3}\\))|)([ 0-9./-]|\\([ 0-9./-]+\\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9./-]|\\([ 0-9./-]+\\)))?$";
var regex0 = new RegExp(r0, "");
The forward-slash has no special meaning, either to regexes or strings. The only reason you ever have to escape forward-slashes is because they're used as the delimiter for regex literals. You use backslashes to escape the forward-slashes just like you do with regex metacharacters like \( or \+, or the backslash itself: \\. Here's the regex-literal version of your regex:
var regex1 = /^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.\/-]|\([ 0-9.\/-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.\/-]|\([ 0-9.\/-]+\)))?$/;
from Errors translating regex from .NET to javascript
The backslash character in JavaScript
strings is an escape character, so the
backslashes you have in your string
are escaping the next character for
the string, not for the regular
expression. So right near the
beginning, in your "^(+?, the
backslash there just escapes the + for
the string (which it doesn't need),
and what the regexp sees is just a raw
+ with nothing to repeat. Hence the error.

javascript \d regular expression unexpected behavior

I am trying use javascript regular expressions to do some matching and I found a really unusual behavior that I was hoping someone could explain.
The string I was trying to match was: " 0 (IR) " and the code block was
finalRegEx = new RegExp("[0-9]");
match = finalRegEx.exec(str);
except that when I put "\d" instead of "[0-9]" it didn't find a match. I'm really confused by this.
If you use RegExp with "\d" to build the regular expression, the "\d" will result in just "d". Either use two back slashes to escape the slash like "\\d" or simply use the regular expression literals /…/ instead:
match = /\d/.exec(str)
You need to escape it because you're using the constructor, otherwise it matches d literally:
new RegExp('\\d').test('1')
new RegExp should only be used for dynamic matching. Otherwise use a literal:
var foo = /\d/;
foo.test(1)
You probably need to escape the backslash: finalRegEx = new RegExp("\\d");

Categories

Resources