code

RegexOptions 열거를 사용하지 않고 대소 문자를 구분하지 않는 Regex

codestyles 2020. 10. 18. 17:57
반응형

RegexOptions 열거를 사용하지 않고 대소 문자를 구분하지 않는 Regex


RegexOptions.IgnoreCase 플래그를 설정하지 않고 Regex 클래스를 사용하여 C #에서 대소 문자를 구분하지 않는 일치를 수행 할 수 있습니까?

내가 할 수 있기를 원하는 것은 정규식 자체 내에서 일치 작업을 대소 문자를 구분하지 않는 방식으로 수행할지 여부를 정의하는 것입니다.

이 정규식을 taylor다음 값과 일치 시키고 싶습니다 .

  • 테일러
  • 테일러
  • 테일러

MSDN 문서

(?i)taylor RegexOptions.IgnoreCase 플래그를 설정하지 않고도 지정한 모든 입력과 일치합니다.

대소 문자 구분을 강제하려면 할 수 있습니다 (?-i)taylor.

다른 옵션은 다음과 같습니다.

  • i, 대소 문자를 구분하지 않음
  • s, 단일 라인 모드
  • m, 다중 회선 모드
  • x, 자유 간격 모드

이미 알고 있듯이 (?i)인라인은 RegexOptions.IgnoreCase.

참고로 할 수있는 몇 가지 트릭이 있습니다.

Regex:
    a(?i)bc
Matches:
    a       # match the character 'a'
    (?i)    # enable case insensitive matching
    b       # match the character 'b' or 'B'
    c       # match the character 'c' or 'C'

Regex:
    a(?i)b(?-i)c
Matches:
    a        # match the character 'a'
    (?i)     # enable case insensitive matching
    b        # match the character 'b' or 'B'
    (?-i)    # disable case insensitive matching
    c        # match the character 'c'

Regex:    
    a(?i:b)c
Matches:
    a       # match the character 'a'
    (?i:    # start non-capture group 1 and enable case insensitive matching
      b     #   match the character 'b' or 'B'
    )       # end non-capture group 1
    c       # match the character 'c'

And you can even combine flags like this: a(?mi-s)bc meaning:

a          # match the character 'a'
(?mi-s)    # enable multi-line option, case insensitive matching and disable dot-all option
b          # match the character 'b' or 'B'
c          # match the character 'c' or 'C'

As spoon16 says, it's (?i). MSDN has a list of regular expression options which includes an example of using case-insensitive matching for just part of a match:

 string pattern = @"\b(?i:t)he\w*\b";

Here the "t" is matched case-insensitively, but the rest is case-sensitive. If you don't specify a subexpression, the option is set for the rest of the enclosing group.

So for your example, you could have:

string pattern = @"My name is (?i:taylor).";

This would match "My name is TAYlor" but not "MY NAME IS taylor".

참고URL : https://stackoverflow.com/questions/2439965/case-insensitive-regex-without-using-regexoptions-enumeration

반응형