Why This JavaScript Regex Doesn't Work

Why this javascript regex doesn't work?

Use a regex literal [MDN]:

var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;

You are making two errors when you use RegExp [MDN]:

  • The "delimiters" / are should not be part of the expression
  • If you define an expression as string, you have to escape the backslash, because it is the escape character in strings

Furthermore, modifiers are passed as second argument to the function.

So if you wanted to use RegExp (which you don't have to in this case), the equivalent would be:

var reg = new RegExp("\\(\\s*([0-9.-]+)\\s*,\\s([0-9.-]+)\\s*\\)", "g");

(and I think now you see why regex literals are more convenient)


I always find it helpful to copy and past a RegExp expression in the console and see its output. Taking your original expression, we get:

/(s*([0-9.-]+)s*,s([0-9.-]+)s*)/g

which means that the expressions tries to match /, s and g literally and the parens () are still treated as special characters.


Update: .match() returns an array:

["(25.774252, -80.190262)", "(18.466465, -66.118292)", ... ]

which does not seem to be very useful.

You have to use .exec() [MDN] to extract the numbers:

["(25.774252, -80.190262)", "25.774252", "-80.190262"]

This has to be called repeatedly until the whole strings was processed.

Example:

var reg = /\(\s*([0-9.-]+)\s*,\s([0-9.-]+)\s*\)/g;
var result, points = [];

while((result = reg.exec(polygons)) !== null) {
points.push([+result[1], +result[2]]);
}

This creates an array of arrays and the unary plus (+) will convert the strings into numbers:

[
[25.774252, -80.190262],
[18.466465, -66.118292],
...
]

Of course if you want the values as strings and not as numbers, you can just omit the +.

Javascript Regex not working on script but working on console

The problem is because your RegExp is not initialized properly.

You can either do:

// Note the \\ to escape the backslash
var reg = new RegExp('^\\d{4}$');

Or

var reg = new RegExp(/^\d{4}$/);

Why regex doesn't work some times in javascript?

Your problem lies on two fronts:

  1. Your var splitStr = str.split(""); line is splitting the string down to individual characters, which means you are never testing '180', but '1', '8', and '0' separately
  2. RegEx is a poor tool to validate numerical range

You should really really really reconsider using regex for this purpose, and instead should parse the input into a number and test it, unless there's some other reason that you need to do it this way. One reason to parse and test instead is that there may be edge cases that your expression doesn't cover, even though they may be valid.

If, for some reason, you absolutely must use regex, you need to test the string(s?) as a whole, rather than char by char, just by using the same RegExp.prototype.test() function like you already were:

function regex1(str) {
return /^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/g.test(str);
}

var tests = ['0', '1', '120', '180', '181'];
for (var str of tests)
console.log(`${str}:`, regex1(str));

Why my regular expression does not work in JavaScript? (It works in Java)

The test method is different from the matches method in Java.

RegEx.prototype.test() returns true whenever a match is found in the string, whereas Matcher.matches() returns true only if the whole string matches the pattern. So the JavaScript test() is more similar to the Java Matcher.find() than to Matcher.matches().

To make your Javascript regexes work, you need to add ^ and $ to assert the start and end of the string:

    var orderNumberRegExp = /^(?:(\d+)|(N\/A))$/

console.log(orderNumberRegExp.test("12345"));



var digitalOnly = /^\d+$/;

console.log(digitalOnly.test("12345"));

console.log(digitalOnly.test("12345ABC"));

Javascript RegEx Not Working

Because you're creating your regular expression from a string, you have to double-up your backslashes:

var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");

When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like

"^(0[1-9]|1[0-2])/\d{4}$"

but after the string parse it's

^(0[1-9]|1[0-2])/d{4}$

Note that \d is now just d.

By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.

There's really no reason here not to use regular expression syntax instead:

var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;

edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.

Why doesn't the following JavaScript Regular Expression work?

It's a grouping problem, as well as an issue with the fact that you don't test for the end of the string using $. Using your expression, Mr.Abc. returns true because it matches ^Mr\.

Change your expression as follows:

let re = /^(Mr|Ms|Mrs|Dr|Er)\.[A-Za-z]+$/;

Why does this javascript regex literal not work?

Well the main issue with your regular expression is that javascript does not support Lookbehind.

re = /(?=[\(\) ])|(?<=[\(\) ])/
^^^ A problem...

Instead, you could possibly use an alternative:

re       = /(?=[() ])|(?=[^\W])\b/;
strSplit = rawQuery.split(re);
console.log(strSplit);

// [ 'hello:', '(', 'world', ' ', 'one', ' ', 'two', ' ', 'three', ')' ]

Regex not working as expected in JavaScript

Your problem is that JavaScript is viewing all your escape sequences as escapes for the string. So your regex goes to memory looking like this:

^(https?://)?([da-z.-]+).([a-z]{2,6})(/(w|-)*)*/?$

Which you may notice causes a problem in the middle when what you thought was a literal period turns into a regular expressions wildcard. You can solve this in a couple ways. Using the forward slash regular expression syntax JavaScript provides:

var urlexp = /^(https?:\/\/)?([da-z\.-]+)\.([a-z]{2,6})(\/(\w|-)*)*\/?$/gi

Or by escaping your backslashes (and not your forward slashes, as you had been doing - that's exclusively for when you're using /regex/mod notation, just like you don't have to escape your single quotes in a double quoted string and vice versa):

var urlexp = new RegExp('^(https?://)?([da-z.-]+)\\.([a-z]{2,6})(/(\\w|-)*)*/?$', 'gi')

Please note the double backslash before the w - also necessary for matching word characters.

A couple notes on your regular expression itself:

[da-z.-]

d is contained in the a-z range. Unless you meant \d? In that case, the slash is important.

(/(\w|-)*)*/?

My own misgivings about the nested Kleene stars aside, you can whittle that alternation down into a character class, and drop the terminating /? entirely, as a trailing slash will be match by the group as you've given it. I'd rewrite as:

(/[\w-]*)*

Though, maybe you'd just like to catch non space characters?

(/[^/\s]*)*

Anyway, modified this way your regular expression winds up looking more like:

^(https?://)?([\da-z.-]+)\.([a-z]{2,6})(/[\w-]*)*$

Remember, if you're going to use string notation: Double EVERY backslash. If you're going to use native /regex/mod notation (which I highly recommend), escape your forward slashes.

Why does the regex stop working when constructed as a string?

When you use the constructed new RegExp () you do not need to escape or enclosing (//) the string. Your second regex may looks like this:

var regex = new RegExp('^(?:533-)?\\d{3}-\\d{4}$');
console.log('533-123-4567'.match(regex));

Refer to the documentation here.

However, the first regex need yo be escape because you are not calling the constructor and you have to precise to the javascript that you are writing is some regex.

regex doesn't work in browser

Description

If you're looking to capture both the head and content at the same time, you could use this expression

::head\n((?:(?!\n+::).)*)\n+::content\n((?:(?!\n+::).)*)$

Regular expression visualization

Example

Live Demo

https://regex101.com/r/oX8vR6/1

Sample text

::head
line 1
line 2
line 3

::content
content 1
content 2
content 3

Sample Matches

  • Capture group 1 gets the values in the head
  • Capture group 2 gets the values in the content
1.  [7-27]  `line 1
line 2
line 3`

2. [39-69] `content 1
content 2
content 3 `

Javascript Code Example:

<script type="text/javascript">
var re = /::head[\r\n]((?:(?![\r\n]+::).)*)[\n\r]+::content[\r\n]((?:(?![\r\n]+::).)*)$/;
var sourcestring = " ---- your sample text goes here ---- ";
var results = [];
var i = 0;
for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) {
results[i] = matches;
for (var j=0; j<matches.length; j++) {
alert("results["+i+"]["+j+"] = " + results[i][j]);
}
i++;
}
</script>

Sample Output

$matches Array:
(
[0] => Array
(
[0] => ::head
line 1
line 2
line 3

::content
content 1
content 2
content 3
)

[1] => Array
(
[0] =>
line 1
line 2
line 3
)

[2] => Array
(
[0] =>
content 1
content 2
content 3
)

)

Explanation

NODE                     EXPLANATION
----------------------------------------------------------------------
::head '::head'
----------------------------------------------------------------------
\n '\n' (newline)
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the most amount
possible)):
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
:: '::'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
. any character except \n
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times (matching
the most amount possible))
----------------------------------------------------------------------
::content '::content'
----------------------------------------------------------------------
\n '\n' (newline)
----------------------------------------------------------------------
( group and capture to \2:
----------------------------------------------------------------------
(?: group, but do not capture (0 or more
times (matching the most amount
possible)):
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times
(matching the most amount possible))
----------------------------------------------------------------------
:: '::'
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
. any character except \n
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
) end of \2
----------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
----------------------------------------------------------------------


Related Topics



Leave a reply



Submit