这应该做你想要的:
Regex regex = new Regex(@"^\t+", RegexOptions.Multiline);
s = regex.Replace(s, m => new string(' ', 4 * m.Value.Length));
在线查看:ideone
更新
这是在 Visual Web Developer 2010 Express 中运行的 ASP.NET Web 窗体版本:
默认.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server" Height="99px" Width="500px" TextMode="MultiLine"></asp:TextBox>
</asp:Content>
默认.aspx.cs
using System;
using System.Text.RegularExpressions;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string code = "protected void Page_Load(object sender, EventArgs e)\n{\n\tResponse.Write(\"Hello World\");\n}";
Regex regex = new Regex(@"^\t+", RegexOptions.Multiline);
TextBox1.Text = regex.Replace(code, m => new string('*', 4 * m.Value.Length));
}
}
}
点击按钮后的结果:
protected void Page_Load(object sender, EventArgs e)
{
****Response.Write("Hello World");
}
星号只是为了方便查看选项卡已正确替换为空格。将 更改'*'
为' '
以获取空格而不是星号。