2015-12-14 170 views
2

我們需要搜索單詞「test.property」,並用一行或多行替換「test1.field」。正則表達式匹配單行或多行的任何單詞[ r n]

字邊界不會忽略\r\n,它可以找到:

test.\r\nproperty 

如何忽略正則表達式C#字與字之間的\r\n

例如:

輸入來源:

int c = test\r\n.Property\r\n["Test"]; 

需要輸出:

int c = test1\r\n.Field\r\n["Test"]; 

我的電流輸出:

int c =test1.Field.["test"] 

模式:

正則表達式我使用的是:

Regex regex = new Regex(@"\btest\s*\.\s*property\b", RegexOptions.IgnoreCase | RegexOptions.Singleline); 
replacementLine = regex.Replace(sourceLine, "test1.field"); 

我們需要只替換字符串不換行。請給出你的建議?

+0

注意你在'propery'一個錯字。只要'@「\ btest \ s * \。\ s * property \ b」'應該這樣做(儘管如此,這將會刪除換行符)。如果你需要用空格「@」\ btest(\ s * \。\ s *)屬性(\ s *)「'替換爲''test1 $ 1field $ 2'''。請參閱[本演示](http://regexstorm.net/tester?p=%5cbtest(%5cs *%5c。%5cs *)屬性(%5cs *)&i = int + c +%3d + test。%0d% 0A ++++++++屬性%0D 0A%%++++++++ 5B%22Test%22%5D%3B%0D 0A%%0D%0aint + C +%3D + test.Property%5B%22Test%22%5D%3B&R = TEST1%241field%242&O = I)。 –

+1

請重新格式化問題,以便清楚您輸入了什麼內容。 –

+0

無論你說的是正確的,但我需要從int c = test替換像 這樣的字符串。\ r \ nProperty \ r \ n [「Test」]; to int c = test1 \ r \ n.method \ r \ n [「Test」],我們只需要替換字符串而不是換行符 – kalimuthu

回答

1

試試這個:

Regex regex = new Regex(@"(?'g1'\btest\b\.\W*)(?'g3'\bproperty\b)", RegexOptions.IgnoreCase | RegexOptions.Singleline); 
var replacementLine = regex.Replace(sourceLine, "${g1}Field"); 
0

你需要回顧後也接受可能空白。這是一個忽略第一個的例子,它改變了第二個和第三個發現。

var data = @"testNO.property['LeaveThis']; 
test 
.property 
['Test']; 

test.property['Test2'];"; 

var pattern = @"(?<=test[\r\n\s]*\.)property"; 

Regex.Replace(data, pattern, "field") 

的結果替換

testNO.property['LeaveThis']; 
test 
.field 
['Test']; 

test.field['Test2']; 
相關問題