developer tip

유니 코드 지원을위한 Java 정규식?

optionbox 2020. 11. 11. 19:58
반응형

유니 코드 지원을위한 Java 정규식?


A와 Z를 일치시키기 위해 정규식을 사용합니다.

[A-Za-z]

정규식이 사용자가 입력 한 utf8 문자와 일치하도록 허용하는 방법은 무엇입니까? 예를 들어 环保 部와 같은 중국어 단어


찾고있는 것은 유니 코드 속성입니다.

예 : \p{L}모든 언어의 모든 종류의 편지

따라서 이러한 중국어 단어와 일치하는 정규식은 다음과 같을 수 있습니다.

\p{L}+

이러한 속성이 많이 있습니다. 자세한 내용은 regular-expressions.info를 참조하십시오 .

또 다른 옵션은 수정자를 사용하는 것입니다.

Pattern.UNICODE_CHARACTER_CLASS

Java 7에는 Pattern.UNICODE_CHARACTER_CLASS미리 정의 된 문자 클래스의 유니 코드 버전을 활성화 하는 새로운 속성 이 있습니다. 자세한 내용과 링크는 여기에서 내 대답을 참조하십시오.

이런 식으로 할 수 있습니다

Pattern p = Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS);

그리고 \w모든 언어에서 모든 문자와 모든 숫자와 일치 (물론 일부 단어의 결합 문자 싶습니다 _).


NLS 지원을 해결하고 영어 특수 문자를 허용하지 않으려면 아래 패턴을 사용할 수 있습니다.

[a-zA-Z0-9 \ u0080- \ u9fff] * +

UTF 코드 포인트 참조 : http://www.utf8-chartable.de/unicode-utf8-table.pl

코드 조각 :

    String vowels = "అఆఇఈఉఊఋఌఎఏఐఒఓఔౠౡ";
    String consonants = "కఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహ";
    String signsAndPunctuations = "కఁకంకఃకాకికీకుకూకృకౄకెకేకైకొకోకౌక్కౕకౖ";
    String symbolsAndNumerals = "౦౧౨౩౪౫౬౭౮౯";
    String engChinesStr = "ABC導字會";


    Pattern ALPHANUMERIC_AND_SPACE_PATTERN_TELUGU = Pattern
            .compile("[a-zA-Z0-9 \\u0c00-\\u0c7f]*+");
    System.out.println(ALPHANUMERIC_AND_SPACE_PATTERN_TELUGU.matcher(vowels)
            .matches());


    Pattern ALPHANUMERIC_AND_SPACE_PATTERN_CHINESE = Pattern
            .compile("[a-zA-Z0-9 \\u4e00-\\u9fff]*+");

    Pattern ENGLISH_ALPHANUMERIC_SPACE_AND_NLS_PATTERN = Pattern
            .compile("[a-zA-Z0-9 \\u0080-\\u9fff]*+");

    System.out.println(ENGLISH_ALPHANUMERIC_SPACE_AND_NLS_PATTERN.matcher(engChinesStr)
            .matches());

개별 문자를 일치 시키려면 리터럴 또는 \u03FB구문을 통해 문자 클래스에 간단히 포함시킬 수 있습니다 .

분명히 표의 언어로 허용되는 모든 문자를 나열 할 수는 없습니다. 정규 표현식이 유형 또는 코드 블록에 따라 유니 코드 문자를 처리하도록하기 위해 여기 에 정의 된 다양한 다른 이스케이프가 지원 됩니다 . "유니 코드 지원"섹션, 특히 Character클래스와 유니 코드 표준 자체에 대한 참조를보십시오 .


  • Java 정규식 API는 char유형에서 작동합니다.
  • the char type is implicitly UTF-16
  • if you have UTF-8 data you will need to transcode it to UTF-16 on input if this is not already being done

Unicode is the universal set of characters and UTF-8 can describe all of it (including control characters, punctuation, symbols, letters, etc.) You will have to be more specific about what you want to include and what you want to exclude. Java regular expressions uses the \p{category} syntax to match codepoints by category. See the Unicode standard for the list of categories.

If you want to identify and separate words in a sequence of ideographs, you will need to look at a more sophisticated API. I would start with the BreakIterator type.

참고URL : https://stackoverflow.com/questions/10894122/java-regex-for-support-unicode

반응형