问题
I have no idea why this isn't working - I've put it through one of the better regex tools I've found on the web to verify it, and I'm using what seems to be the escape character '\' before the + sign to make it a literal '+', but Google Scripts keeps complaining saying "Invalid Quantifier '+'" (Line 2)
Here's my script, with certain personal details (it's to clean out email as I use this account as a hard spam filter) omitted:
function getEmailData() {
var find_email_regex = new RegExp("myemail(\+.*|)\@gmail.com");
var emails = GmailApp.getChatThreads();
var process_email = "";
try {
for (i = 0; i < emails.length; i++) {
for (x = 0; x < emails[i].getTo().length; x++) {
if (emails[i].getTo()[x].matches(find_email_regex)) {
email_triage(emails[i]);
break;
}
}
}
} catch (e) {}
}
function email_triage(email) {
var reject_regex = new RegExp("^[^\+]*$");
try {
if (email.matches(reject_regex)) {
email.moveThreadToTrash();
}
else {
email.getMessages()[0].forward("mymainemail@email.ca");
}
} catch (e) {}
}
Is there any obvious reason as to why it keeps saying invalid quantifier? My objective is to regex two variations of my address, since a spammer might send an email with a large list, and I only want to parse my email out of it for further processing.
It needs to handle: myemail+stuff@gmail.com myemail@gmail.com
Hence the literal, but I have no luck with it. Please assist, thank you.
回答1:
You can use the following:
RegExp("myemail(\\+.*?|)@gmail\\.com");
^ ^ ^ ^^
- You need to escape the escape character (double escape for special characters)
- escape the dot before
com
- and no need to escape
@
- also make the
.*
non greedy
回答2:
You need to double escape the \
as it is a string escape character
new RegExp("myemail(\\+.*|)@gmail\\.com");
回答3:
As others say, the string literal is eating your backslash, so regexp is left with none. You can double up on backslashes, or you can use the regexp literal instead of converting a string into a regexp:
var find_email_regex = /myemail(\+.*|)@gmail\.com/;
Advantage: more legible (and should even be a smidgen faster, given that you are creating only one object instead of two).
来源:https://stackoverflow.com/questions/30318183/escape-regex-literal-in-google-apps-script