C#正则表达式:除去开头和结尾的双引号(") [英] C# Regular Expression: Remove leading and trailing double quotes (")

查看:2014
本文介绍了C#正则表达式:除去开头和结尾的双引号(")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有像下面的字符串...什么是正则表达式来删除(可选)前缘和后双引号?对于额外的信用,可以把它也删除任何可选空格引号外:

If I have a string like below... what is the regular expression to remove the (optional) leading and trailing double quotes? For extra credit, can it also remove any optional white space outside of the quotes:

string input = "\"quoted string\""   -> quoted string
string inputWithWhiteSpace = "  \"quoted string\"    "  => quoted string



(对于C#中使用Regex.Replace)

(for C# using Regex.Replace)

推荐答案

这是矫枉过正使用 Regex.Replace 这一点。使用 修剪 来代替。

It's overkill to use Regex.Replace for this. Use Trim instead.

string output = input.Trim(' ', '\t', '\n', '\v', '\f', '\r', '"');

如果你只想要删除空格那的之外的报价,留住任何这里面的:

And if you only want to remove whitespace that's outside the quotes, retaining any that's inside:

string output = input.Trim().Trim('"');

这篇关于C#正则表达式:除去开头和结尾的双引号(")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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