2013-12-19 82 views
0

我有一個字符串,我需要解析到一個XElement進一步處理(我沒有控制輸入字符串,這是實際XML的簡化版本,但足以證明問題):如何刪除前導左箭頭和尾隨文本之間的空白?

string inputXML = @" 
    < 
    blahblahblahblahblah>"; 

我試圖在打開左箭頭後立即刪除回車&空格(XElement將不會用打開的左箭頭之後的前導空格解析它)。以下是我已經試過:

//tried making new strings instead of reusing the existing one, 
//didn't make any difference 
string test = inputXML.Replace("\r\n",""); 
string test2 = test.Replace(@"^<\s+", "<"); 
Console.WriteLine(test2); 

這導致一個字符串,它看起來像這樣:

<  blahblahblahblahblah> 

取而代之的是:

<blahblahblahblahblah> 

除上述以外,我還嘗試:

inputXML.Replace(@"<[ ]+", "<"); //doesn't work 
inputXML.Replace(@"< +", "<"); //doesn't work 
inputXML.Replace(@"<\040+", "<"); //doesn't work 
inputXML.Replace(@"<  ", "<"); //works!, but not very useful and I don't 
//understand why I need twice as many spaces as the actual number? Since I don't 
//control the input, this isn't a solution, it only happens to work for this one. 

我'我很確定我錯過了一些愚蠢的東西。所有這些正則表達式都可以在www.rubular.com中工作,我認爲它適用於Ruby,但它對測試非常方便。

我也沒有結婚這樣做與正則表達式,所以如果你有另一個建議,我都耳朵。

我不認爲它是密切相關的,但我在LINQPad中測試這個。

+2

難道你只是[修剪](http://msdn.microsoft.com/en-us/library/system.string.trim(v = vs.110).aspx)extra白色空間? – Brian

+1

我徹底推薦Rad Software Regular Expression Designer用於烹飪.Net正則表達式。它看起來像Rad Software不在了,但該工具在其他地方仍然可用。 – spender

+1

@Brian在這種情況下如何修剪工作?修剪僅刪除前導字符和尾隨字符,而不是字符串中間的任何字符。 – AaronS

回答

2

你有兩個問題:

  1. string.Replace不使用正則表達式的工作。改爲使用Regex.Replace
  2. ^錨定在字符串中意味着<必須出現在字符串的開頭。如果您只是想在第一個<後刪除空格,請移除錨點。

試試這個:

string test = inputXML.Replace("\r\n",""); 
string test2 = Regex.Replace(test, @"<\s*", "<"); 
Console.WriteLine(test2); // " <blahblahblahblahblah>" 

或者,如果你也想在<之前刪除任何空白,使用此:

string test = inputXML.Replace("\r\n",""); 
string test2 = Regex.Replace(test, @"\s*<\s*", "<"); 
Console.WriteLine(test2); // "<blahblahblahblahblah>" 
+0

我沒有意識到這一點。更換沒有與正則表達式,謝謝你解釋這對我。當你使用正確的工具時,它會簡單得多。您使用Regex.Replace()的更改完美地工作。 – delliottg

2

由於XML的任意內容,這可能只能安全地刪除位於標籤內的空白。所以:

string inputXML = @" 
< 
blahblahblahblahblah>"; 
string pattern = @"(?<=\<)\s+"; //match one or more whitespace following a < 
var cleaned = Regex.Replace(inputXML, 
          pattern, 
          string.Empty, 
          RegexOptions.Multiline) 
+0

正如我向上面的AaronS解釋的那樣,我應該在我的例子中包含一個節點。如果它們存在,我必須保留用戶輸入的筆記,所以我不能刪除所有空格,我必須非常精確地刪除所有空格。即使有這樣的警告,我懷疑你的版本可能會有效(我會盡快測試)。我只是重新閱讀你的解釋,這也應該工作,因爲它只能在標籤內工作。你能解釋一下這個正則表達式嗎?我不明白什麼是問號和等號。 – delliottg

相關問題