问题
I'm currently working with a regular expression (in Javascript) for replacing double quotes with smart quotes:
// ie: "quotation" to “quotation”
Here's the expression I've used for replacing the double quotes:
str = str.replace(/"([A-Za-z ]*)"/ig, "“$1”")
The above works perfectly if the phrase inside the quotes contains no additional punctuation, however, I also need to replace any apostrophes:
// ie: replace "It's raining again" with “It’s raining again!”
The expression for replacing single quotes/ apostrophes works fine if not encapsulated:
str.replace(/\'\b/g, "’"); // returns it's as it’s correctly
// Using both:
str.replace(/"([A-Za-z ]*)"/ig, "“$1”").replace(/\'\b/g, "’");
// "It's raining again!" returns as "It’s raining again!"
// Ignores double quotes
I know this is because the expression for replacing the double quotes is being matched to letters only, but my limited experience with regular expressions has me flummoxed at how to create a match for quotations that may also contain single quotes!
Any help would be HUGELY appreciated! Thanks in advance.
回答1:
You can include in quotes all except quotes:
str = str.replace(/"([^"]*)"/ig, "“$1”")
Another option: use non-greedy search:
str = str.replace(/"(.*?)"/ig, "“$1”")
Also I'm not sure that you need to change only single quotes that are at the end of a word. May be it were better to change all of them?
replace(/\'/g, "’");
回答2:
You can search for anything not a "
. I would also make a lazy match with ?
in case you had something like "Hey," she said, "what's up?"
as your str
:
str.replace(/"([^"]*?)"/ig, "“$1”").replace(/\'\b/g, "’");
回答3:
Just to add to the current answers, you are performing a match on [A-Za-z ]*
for the double quote replace, which means "match uppercase, lowercase or a space". This won't match It's raining
, since your match expression does not contain the single quote.
Follow the advice of matching "anything but another double quote", since with your original regex a string like She said "It's raining outside." He said "really?"
will result in She said ”It's raining outside." He said "really?”
(the greedy match will skip past the 'inner' double quotes.)
回答4:
It's a good idea to limit the spesific characters left and right of the quotes, especially if this occurs in a html file. I am using this.
str = str.replace(/([\n >*_-])"([A-Za-z0-9 ÆØÅæøå.,:;!#@]*)"([ -.,!<\n])/ig, "$1«$2»$3");
In this way, you avoid replacing quotes inside html-tags like href="http.....
Normaly, there is an space left of the opening quote, and another right of the closing quote. In html document, it might be a closing bracket, a new line, etc. I have also included the norwegian characters. :-)
来源:https://stackoverflow.com/questions/11616550/regular-expression-for-apostrophes-single-quotes-with-double