Programming/Regex

[펌] C# - 정규식을 이용한 문자 변환

blueasa 2016. 4. 15. 10:42

정규식을 이용하여 특정 문자만 얻는 방법을 알아보겠습니다.

 

- Namespace : System.Text.RegularExpressions

- Class : Regex

- Method : 

 

 public static string Replace(
string input,
string pattern,
string replacement
 )

 

 

1. 숫자만 얻기

 - 정규식 : [^0-9]

1
2
3
4
5
6
string str = "Englsh@korea$101299**한글";
 
// 숫자만 0-9
str = Regex.Replace(str, @"[^0-9]""");
 
// 결과 : 101299
cs

2. 영문자만 얻기

 - 정규식 : [^a-zA-Z]

1
2
3
4
5
6
string str = "Englsh@korea$101299**한글";
 
// 영문자 a-z A-Z
str = Regex.Replace(str, @"[^a-zA-Z]""");
 
// 결과 : Englshkorea
cs

 

3. 한글만 얻기

 - 정규식 : [^가-힣]

1
2
3
4
5
6
string str = "Englsh@korea$101299**한글";
 
// 한글만 가-힣
str = Regex.Replace(str, @"[^가-힣]""");
 
// 결과 : 한글
cs

 

4. 특수문자 제거

  - 정규식 : [^0-9a-zA-Z가-힣]

1
2
3
4
5
string str = "Englsh@korea$101299**한글";
// 특수문자 제거
str = Regex.Replace(str, @"[^0-9a-zA-Z가-힣]""");
 
// 결과 : Englshkorea101299한글
cs

 

※ 위의 예에서와 같이 정규식을 잘 이용하면 얻고자 하는 문자를 쉽게 처리 할 수 있습니다.

 

 

[출처]

http://docko.tistory.com/entry/C-%EC%A0%95%EA%B7%9C%EC%8B%9D%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%AC%B8%EC%9E%90-%EB%B3%80%ED%99%98

반응형