除第一个和最后一个字符外的正则表达式替换 [英] Regular expression replace except first and last characters

查看:37
本文介绍了除第一个和最后一个字符外的正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用转义反斜杠后跟双引号 (\") 替换字符串中的双引号 (") 的正则表达式是什么,除了字符串的第一个和最后一个字符.

示例 1:嵌入在字符串中的双引号

输入:这是一个测试""预期输出:这是一个\"测试\"

示例 2:字符串中间没有双引号

输入:这是一个测试"预期输出:这是一个测试"

当我在 python 中执行 re.sub() 操作时,包括第一个和最后一个双引号字符在内的所有内容都将被替换.在我上面的例子中,输出字符串变成:\"This is a Test\".

解决方案

正如@mgilson 所指出的,你可以将第一个和最后一个字符切掉,所以这个正则表达式基本上毫无意义

<预><代码>>>>print re.sub(r'(?<!^)"(?!$)', '\\"', '"This is a "Test""')这是一个测试\"">>>print re.sub(r'(?<!^)"(?!$)', '\\"', '"这是一个测试"')这是一个测试"

What is a regular expression to replace doublequotes (") in a string with escape backslash followed by doublequotes (\") except at the first and last characters of the string.

Example 1: Double quote embedded in a string

Input: "This is a "Test""
Expected Output: "This is a \"Test\""

Example 2: No double quotes in the middle of the string

Input: "This is a Test"
Expected Output: "This is a Test"

When I perform a re.sub() operation in python, everything including the first and last doublequote characters are getting replaced. In my example above, the output string becomes: \"This is a Test\".

解决方案

As pointed out by @mgilson, you can just slice the first and last characters off so this regex is basically pointless

>>> print re.sub(r'(?<!^)"(?!$)', '\\"', '"This is a "Test""')
"This is a \"Test\""
>>> print re.sub(r'(?<!^)"(?!$)', '\\"', '"This is a Test"')
"This is a Test"

这篇关于除第一个和最后一个字符外的正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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