单引号/双引号的正则表达式 [英] Regular expression for apostrophes/ single quotes with double

查看:153
本文介绍了单引号/双引号的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用正则表达式(使用Javascript)将双引号替换为智能引号:

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.

推荐答案

最好限制引号左右的特殊字符,尤其是在html文件中.我正在用这个.

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");

通过这种方式,您避免在html-tag之类的href标记中替换引号,例如href ="http .....

In this way, you avoid replacing quotes inside html-tags like href="http.....

通常,在开始报价的左边有一个空格,而在结束报价的右边有一个空格.在html文档中,它可能是一个右括号,换行符等.我还包括了挪威字符.:-)

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. :-)

这篇关于单引号/双引号的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆