我有一個字符串,我需要解析到一個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中測試這個。
難道你只是[修剪](http://msdn.microsoft.com/en-us/library/system.string.trim(v = vs.110).aspx)extra白色空間? – Brian
我徹底推薦Rad Software Regular Expression Designer用於烹飪.Net正則表達式。它看起來像Rad Software不在了,但該工具在其他地方仍然可用。 – spender
@Brian在這種情況下如何修剪工作?修剪僅刪除前導字符和尾隨字符,而不是字符串中間的任何字符。 – AaronS