2012-07-29 44 views
1

我正在格式化HTML中的C#代碼。我試圖用4個空格替換製表符/縮進。查找標籤或4個空格(在C#代碼中)

下面是一個例子。

protected void Page_Load(object sender, EventArgs e) 
{ 
    Response.Write("Hello World"); 
} 

我需要替換Response.Write之前的選項卡與4個空格。

我試過^ \ t之類的東西,不同的變化,試過^ \ s \ s \ s \ s。我認爲這很簡單,但我沒有試過似乎與標籤相匹配。

我在做什麼錯?

謝謝!

編輯

我直接從VS複製到TextBox1的。

enter image description here

正如你可以看到,有是在TextBox值,這是問題的根源沒有實際翼片(\噸)。正如我在評論中指出的那樣,有^的空間確實有效(僅適用於第一行)。

所以我最終的正則表達式看起來像這樣:「\ s \ s \ s \ s」。

+0

嘗試'\ n \ t'與'\更換ñ'或檢查您對多行模式在你的正則表達式 – 2012-07-29 21:46:11

+0

應在代碼中的其他地方的標籤會發生什麼?保持不變? – 2012-07-29 21:46:40

+2

該選項卡是否始終位於字符串的開頭? – Daniel 2012-07-29 21:47:04

回答

3

這應該做你想要什麼:

Regex regex = new Regex(@"^\t+", RegexOptions.Multiline); 
s = regex.Replace(s, m => new string(' ', 4 * m.Value.Length)); 

網上看到它:ideone


更新

下面是ASP.NET Web窗體版本,在視覺上運行Web Developer 2010 Express:

Default.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> 

Default.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"); 
} 

的星號在那裏只是爲了讓您輕鬆看標籤已被正確替換爲空格。將'*'更改爲' '以獲取空格而不是星號。

+0

奇怪的是,相同的代碼不適用於我(來自ideone)。 – Rivka 2012-07-29 22:00:13

+0

@Rivka:可能是您的編譯器或編輯器設置。它可以工作,但請注意它使用'「*」'而不是''「'(所以你可以看到不同之處)。 – 2012-07-29 22:03:06

+0

我直接從VS 2012複製/粘貼 - 不起作用。我注意到在調試模式下,值是「protected void Page_Load(object sender,EventArgs e)\ r \ n {\ r \ n Response.Write(\」Hello World \「); \ r \ n} 「\ r \ n」後有4個空格)。當我用「\ s \ s \ s \ s」替代「\ t」時,它適用於第一行。 – Rivka 2012-07-29 22:33:33

0
string text = "\tHello World"; 
string replacedTabWith4Spaces = text.Replace("\t", " "); 
+0

這與靜態「\ t」一起工作,但在我的情況下沒有幫助。 – Rivka 2012-07-29 22:34:54