2016-08-22 4 views
0

c를 정규식을 사용하여 텍스트의 일부를 대체 : 방법, 예를 들어 #

string str = [email protected]"<html> <head> </ head > <body> <start> <h1> Header 1 </ h1 > <p> A worker can be of 3 different types.</ p > <end> <p></ p > </ body > </ html > " 
string replacement = "hello world"; 
string newString = [email protected]"<html> <head> </ head > <body> <start> <h1> Header 1 </ h1 > <p> hello world</ p > <end> <p></ p > </ body > </ html > " 

그래서 내가 교체해야 할 텍스트의 일부 알아야 할 <start><end> 기호가 있습니다. 정규식으로 newString을 얻는 방법.

답변

1

Regex.Replace을 사용하면 <r>의 첫 번째 패턴부터 두 번째 패턴까지 패턴을 설정할 수 있습니다. 그런 다음 대체 할 대상을 지정합니다.

var result = Regex.Replace(str, "<start>.*?<end>", $"<start> {replacement} <end>"); 

경우 C# 6.0 문자열 보간 이전 : 의견에서 최신 문자열로

var result = Regex.Replace(str, "<start>.*?<end>", string.Format("<start> {0} <end>",replacement)); 

:

string str = [email protected]"<html> <head> </ head > <body> <start> <h1> Header 1 </ h1 > <p> A worker can be of 3 different types.</ p > <end> <p></ p > </ body > </ html > "; 
string replacement = "hello world"; 

var result = Regex.Replace(str, "<start>.*?<end>", $"<start> {replacement} <end>"); 
+0

이 정규식 너무 간단합니다. 보다 효율적인 String.Replace() 메소드를 사용하십시오. – jdweng

+0

답변을 주셔서 감사하지만 도움이되지 않았습니다. –

+0

@DoniyorNiyozov - "도움을받지 못했다"는 것은 무엇을 의미합니까? 그것은 나를 위해 작동합니다. 어떤 C#을 사용하고 있습니까? C# 6.0 이하인 경우 업데이트 –