String.Replace가 "전체 단어"를 누르는 방법
이것을 가질 방법이 필요합니다.
"test, and test but not testing. But yes to test".Replace("test", "text")
이것을 반환하십시오 :
"text, and text but not testing. But yes to text"
기본적으로 전체 단어를 바꾸고 싶지만 부분 일치는 아닙니다.
참고 :이 작업에는 VB (SSRS 2008 코드)를 사용해야하지만 C #은 일반적인 언어이므로 둘 중 하나의 응답은 괜찮습니다.
정규식은 가장 쉬운 방법입니다.
string input = "test, and test but not testing. But yes to test";
string pattern = @"\btest\b";
string replace = "text";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);
패턴의 중요한 부분은 \b
단어 경계에서 일치 하는 메타 문자입니다. 대소 문자를 구분하지 않으려면 RegexOptions.IgnoreCase
다음을 사용하십시오 .
Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);
Ahmad Mageed가 제안한 정규 표현식을 래핑 하는 함수 ( 여기 블로그 게시물 참조 )를 만들었습니다.
/// <summary>
/// Uses regex '\b' as suggested in https://stackoverflow.com/questions/6143642/way-to-have-string-replace-only-hit-whole-words
/// </summary>
/// <param name="original"></param>
/// <param name="wordToFind"></param>
/// <param name="replacement"></param>
/// <param name="regexOptions"></param>
/// <returns></returns>
static public string ReplaceWholeWord(this string original, string wordToFind, string replacement, RegexOptions regexOptions = RegexOptions.None)
{
string pattern = String.Format(@"\b{0}\b", wordToFind);
string ret=Regex.Replace(original, pattern, replacement, regexOptions);
return ret;
}
Sga가 언급했듯이 정규식 솔루션은 완벽하지 않습니다. 그리고 성능도 좋지 않은 것 같습니다.
내 공헌은 다음과 같습니다.
public static class StringExtendsionsMethods
{
public static String ReplaceWholeWord ( this String s, String word, String bywhat )
{
char firstLetter = word[0];
StringBuilder sb = new StringBuilder();
bool previousWasLetterOrDigit = false;
int i = 0;
while ( i < s.Length - word.Length + 1 )
{
bool wordFound = false;
char c = s[i];
if ( c == firstLetter )
if ( ! previousWasLetterOrDigit )
if ( s.Substring ( i, word.Length ).Equals ( word ) )
{
wordFound = true;
bool wholeWordFound = true;
if ( s.Length > i + word.Length )
{
if ( Char.IsLetterOrDigit ( s[i+word.Length] ) )
wholeWordFound = false;
}
if ( wholeWordFound )
sb.Append ( bywhat );
else
sb.Append ( word );
i += word.Length;
}
if ( ! wordFound )
{
previousWasLetterOrDigit = Char.IsLetterOrDigit ( c );
sb.Append ( c );
i++;
}
}
if ( s.Length - i > 0 )
sb.Append ( s.Substring ( i ) );
return sb.ToString ();
}
}
... 테스트 케이스 포함 :
String a = "alpha is alpha";
Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alphonse" ) );
Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alf" ) );
a = "alphaisomega";
Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) );
a = "aalpha is alphaa";
Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) );
a = "alpha1/alpha2/alpha3";
Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "xxx" ) );
a = "alpha/alpha/alpha";
Console.WriteLine ( a.ReplaceWholeWord ( "alpha", "alphonse" ) );
I just want to add a note about this particular regex pattern (used both in the accepted answer and in ReplaceWholeWord function). It doesn't work if what you are trying to replace isn't a word.
Here a test case:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string input = "doin' some replacement";
string pattern = @"\bdoin'\b";
string replace = "doing";
string result = Regex.Replace(input, pattern, replace);
Console.WriteLine(result);
}
}
(ready to try code: http://ideone.com/2Nt0A)
This has to be taken into consideration especially if you are doing batch translations (like I did for some i18n work).
If you want to define what characters make up a word i.e. "_" and "@"
you could use my (vb.net) function:
Function Replace_Whole_Word(Input As String, Find As String, Replace As String)
Dim Word_Chars As String = "ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyxz0123456789_@"
Dim Word_Index As Integer = 0
Do Until False
Word_Index = Input.IndexOf(Find, Word_Index)
If Word_Index < 0 Then Exit Do
If Word_Index = 0 OrElse Word_Chars.Contains(Input(Word_Index - 1)) = False Then
If Word_Index + Len(Find) = Input.Length OrElse Word_Chars.Contains(Input(Word_Index + Len(Find))) = False Then
Input = Mid(Input, 1, Word_Index) & Replace & Mid(Input, Word_Index + Len(Find) + 1)
End If
End If
Word_Index = Word_Index + 1
Loop
Return Input
End Function
Test
Replace_Whole_Word("We need to replace words tonight. Not to_day and not too well to", "to", "xxx")
Result
"We need xxx replace words tonight. Not to_day and not too well xxx"
You could use the string.replace
string input = "test, and test but not testing. But yes to test";
string result2 = input.Replace("test", "text");
Console.WriteLine(input);
Console.WriteLine(result2);
Console.ReadLine();
참고URL : https://stackoverflow.com/questions/6143642/way-to-have-string-replace-only-hit-whole-words
'Development Tip' 카테고리의 다른 글
bash에서 fork 및 exec (0) | 2020.11.10 |
---|---|
subclipse : 기본 SVN 클라이언트를로드 할 수 없습니다. (0) | 2020.11.10 |
OSX 10.7 Lion의 JDK (0) | 2020.11.10 |
Oh My Zsh- '업데이트를 확인 하시겠습니까?'프롬프트 비활성화 (0) | 2020.11.10 |
Rails 4 강력한 매개 변수 : 모든 속성을 허용합니까? (0) | 2020.11.10 |