Nodejs regexp error: "Invalid regular expression: nothing to repeat" - javascript

So I have this regular expression:
(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#exclude[ \t]*([^\n*]*)[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?((?:.|\n|\r)*?)(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#endexclude[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?
Which is supposed to match anything that looks like this:
/* #exclude */
hurdur = somerandomtextorcode;
/* #endexclude */
I am trying this regular expression in tools such as https://regex101.com/ (https://regex101.com/r/eA5oK9/1) and there it just simply works, no errors.
However, in the nodejs environment, I get this error which I really do not know how to solve:
Warning: Invalid regular expression: /(?:[ ]*)?(?://|/*)[ ]*#exclude[
]*([^
]*)[ ]*(?:*/)?(?:[ ]*[
]+)?((?:.|
|
)?)(?:[ ]*)?(?://|/*)[ ]*#endexclude[ ]*(?:*/)?(?:[ ]*[
]+)?/: Nothing to repeat Use --force to continue.
Any help on this would be greatly appreciated!

Alright, it turns out it was a problem related to the way I was actually creating the regular expression.
I was creating (and applying) the regular expression like this:
var rExclude = '(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#exclude[ \t]*([^\n*]*)[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?((?:.|\n|\r)*?)(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#endexclude[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?';
contents = contents.replace(new RegExp(rExclude, 'gi'), function () { return ""; });
This gives me the error that is described in the starting post.
However, because the regular expression is in a string, JavaScript decides it wants to handle the regular expression differently. You can fix it in two ways:
Solution 1
This solution alters the way stuff is being escaped in your string.
var rExclude = '(?:[ \t]*)?(?://|/\\*)[ \t]*#exclude[ \t]*(?:\\*/)?(?:.|\n|\r)*?(?://|/\\*)[ \t]*#endexclude[ \t]*(?:\\*/)?';
contents = contents.replace(new RegExp(rExclude, 'gi'), function () { return ""; });
Solution 2
This solution alters the way the actual regular expression is being created:
contents = contents.replace(/(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#exclude[ \t]*(?:\*\/)?(?:.|\n|\r)*?(?:\/\/|\/\*)[ \t]*#endexclude[ \t]*(?:\*\/)?/gi, function () { return ""; });
It's just another weird ass JavaScript quirk, unfortunately.

Double-up your backslashes.
Notice how here: (?:*/)? there's no backslash? This means your * is trying to repeat.. nothing. Nothing to repeat.

Related

JavaScript: Can I use the filter function with regular expressions?

I tried to find a similar question to avoid creating a duplicate and I couldn’t, but I apologise if I missed any. I've just started learning how to code and I've encountered this problem:
With JavaScript, I want to use the filter arrays method (https://www.freecodecamp.org/challenges/filter-arrays-with-filter) with a general expression for all non alphanumeric characters.
For example:
var newArray = oldArray.filter(function(val) {
return val !== /[\W_]/g;
});
Can I do that? In the mozilla guide (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) it mentions you can use regular expressions with replace, and I understand how to do that, but it doesn’t mention filter at all.
To put another less abstract example, this is the code I’m working on:
function palindrome(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
return val !== /[\W_]/g;
});
return filterArray;
}
palindrome("ey*e");
If I’m doing things right so far, the function should return [“e”, “y”, “e”]. But it returns [“e”, “y”, “*”, “e”] (as if I hadn’t filtered it at all). I just wonder if I’ve made a mistake in my code, or if one simply can’t use filter with regular expressions.
If that's the case, why? Why can't one use filter with regular expressions!? Why do we have to use replace instead?
This really isn't an issue relating to .filter(), it's just that you aren't testing your string against your regular expression properly.
To test a string against a regular expression you use the .test() method:
function palindrome(str) {
var splitStr = str.split("");
var filterArray = splitStr.filter(function(val) {
// Test the string against the regular expression
// and test for no match (whole thing is preceeded by !)
return !/[\W_]/g.test(val);
});
return filterArray;
}
console.log(palindrome("ey*e"));
Instead of first splitting the string into chars, and then test every single one of them, why don't you just get all matches for the string?
function palindrome(str) {
return str.match(/[a-zA-Z0-9]/g) || [];
}
let chars = palindrome("ey*e");
console.log(chars);
About the used regex: \W is the same as [^\w] or [^a-zA-Z0-9_]. So, not [\W_] is equivalent to [a-zA-Z0-9].

regular expression not matching on javascript but matches on other languages

so I've been running around regexp for a while now, and been using RegEx101 to test my patterns, and it never failed (yet).
So I am trying to replace android Emojicons strings to their appropriate HTML image tage via regex, the code seems to match without an issue in the site above, and even works with PHP, but somehow, it doesn't match at all in javascript... so here is my code:
function loadEmojisInMessage(message) {
var regExp = /({emoji:(.*?)})/g; //var regExp = new RegExp("({emoji:(.*?)})","g");
message.replace(regExp, '<img src="emojis/emoji_$2.png" id="$2" class="emojicon" />').toString();
return message;
}
at first I thought I am doing something wrong, so I changed the code to this, just for testing
function loadEmojisInMessage(message) {
var regExp = /({emoji:(.*?)})/g; //var regExp = new RegExp("({emoji:(.*?)})","g");
message.replace(regExp, 'test?').toString();
return message;
}
but even this does not replace at all! (my thought is that it is having an issue matching the pattern in the string :/ )
example strings to match :
{emoji:em_1f50f}
What I am trying to do here is replace the entire string (above) with image HTML tag, while using the second match [it is the second bracket () ] for the URL string
Best Regards
UPDATE :
I forgot to add first matching bracket, sorry!
Also, you can test the pattern here
You're not assigning the result of the replace() method call back to the variable message. If you don't to this, message remains unchanged.
message = message.replace(regExp, '<img src="emojis/emoji_$2.png" id="$2" class="emojicon" />');

SyntaxError: unterminated parenthetical for validating the local file path

I have to validate the local folder path which is in the following format : ..\sentinel\log .
I have old regular expression ( /[\w]:\.*/)) for C:\sentinel\log and that was working. I need to make accept this path.
I have the following expresion from regexplibrary
var pathRE = new RegExp("/^((../|[a-zA-Z0-9_/-\])*.[a-zA-Z0-9])"); Error :
SyntaxError: unterminated parenthetical
When i executing is throw this error
I am attaching the code that i have tried
function checkFolderpath(path) {
try {
//var pathRE = new RegExp(/[\w]:\\.*/);
var pathRE = new RegExp("/^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9])");
if (pathRE.test(path)) {
$("#spanloggererror").html("");
return true;
}
else {
$("#spanloggererror").html(resx_Invalid_Loggerpath);
valtemp = 1;
}
return false;
}
catch (err) {
alert(err.Message);
}
Please suggest me how to fix the issue.
Edit :
value of path : ..\Sentinel\log
Your regular expression should be constructed like this:
var pathRE = /^((..\/|[a-zA-Z0-9_/-\\])*.[a-zA-Z0-9])/;
The only time you really need to use the RegExp constructor is when you're building up a regular expression from separate pieces, dynamically. You have to be careful with quoting forward-slash characters in the expression (/) when you use native regular expression syntax. You don't have to quote them inside [ ] groups, but you do need to double your backslashes.
That regular expression won't match ..\what\ever because it only looks for forward slash at the start. It also won't match a terminal file name longer than two characters. I think a better one would be:
var pathRE = /^\.\.(?:\\[A-Za-z0-9_-]+)+/;
with appropriate changes for the file name characters you expect.
Escape the slash:
/^((\.\./|[a-zA-Z0-9_\/\-\\])*\.[a-zA-Z0-9])/
// here __^ and add slash __^

Regular Expression to validate email: illegal character

Doing form validation using Jquery without plugins, they're easy enough to use. Trying to teach myself regular expressions and at a wall.
var email = $('#email').val();
// Validate email address
// Regular expression to match email address:
var emailReg = \S+#\S+;
if(email.match(emailReg)) {
// Pass
}
else {
// Fail
$('#email').css("background","yellow");
var counter2 = setTimeout("$('#email').css('background','white')", 3000);
return false;
}
I know it's the worlds simplest regular expression, just trying to get functionality and I'll get more sophisticated later.
Keep getting SyntaxError: illegal character \S (here) +#S+
Don't understand why. Have searched this site and tried dozens always with console errors.
Add / around it.
var emailReg = /\S+#\S+/;
^ ^
You need to place your regex in forwardslashes like so:
var emailReg = /\S+#\S+/;
This way it knows it's a regex object, instead of just random operators put together
You could also do:
var emailReg = new RegExp("\S+#\S+");
This method is useful if you aren't just writing a static regex (eg. getting the regex from user input)
Regular expressions are enclosed in forward slashes in js. Try
var emailReg = /\S+#\S+/;

Javascript string validation using the regex object

I am complete novice at regex and Javascript. I have the following problem: need to check into a textfield the existence of one (1) or many (n) consecutive * (asterisk) character/characters eg. * or ** or *** or infinite (n) *. Strings allowed eg. *tomato or tomato* or **tomato or tomato** or as many(n)*tomato many(n)*. So, far I had tried the following:
var str = 'a string'
var value = encodeURIComponent(str);
var reg = /([^\s]\*)|(\*[^\s])/;
if (reg.test(value) == true ) {
alert ('Watch out your asterisks!!!')
}
By your question it's hard to decipher what you're after... But let me try:
Only allow asterisks at beginning or at end
If you only allow an arbitrary number (at least one) of asterisks either at the beginning or at the end (but not on both sides) like:
*****tomato
tomato******
but not **tomato*****
Then use this regular expression:
reg = /^(?:\*+[^*]+|[^*]+\*+)$/;
Match front and back number of asterisks
If you require that the number of asterisks at the biginning matches number of asterisks at the end like
*****tomato*****
*tomato*
but not **tomato*****
then use this regular expression:
reg = /^(\*+)[^*]+\1$/;
Results?
It's unclear from your question what the results should be when each of these regular expressions match? Are strings that test positive to above regular expressions fine or wrong is on you and your requirements. As long as you have correct regular expressions you're good to go and provide the functionality you require.
I've also written my regular expressions to just exclude asterisks within the string. If you also need to reject spaces or anything else simply adjust the [^...] parts of above expressions.
Note: both regular expressions are untested but should get you started to build the one you actually need and require in your code.
If I understand correctly you're looking for a pattern like this:
var pattern = /\**[^\s*]+\**/;
this won't match strings like ***** or ** ***, but will match ***d*** *d or all of your examples that you say are valid (***tomatos etc).If I misunderstood, let me know and I'll see what I can do to help. PS: we all started out as newbies at some point, nothing to be ashamed of, let alone apologize for :)
After the edit to your question I gather the use of an asterisk is required, either at the beginning or end of the input, but the string must also contain at least 1 other character, so I propose the following solution:
var pattern = /^\*+[^\s*]+|[^\s*]+\*+$/;
'****'.match(pattern);//false
' ***tomato**'.match(pattern);//true
If, however *tomato* is not allowed, you'll have to change the regex to:
var pattern = /^\*+[^\s*]+$|^[^\s*]+\*+$/;
Here's a handy site to help you find your way in the magical world of regular expressions.

Categories

Resources