programing

공백 매칭 정규식 - Java

goodcopy 2022. 9. 25. 23:08
반응형

공백 매칭 정규식 - Java

정규 표현의 Java API는 다음과 같이 기술되어 있습니다.\s공백과 일치합니다. \\s\\s2번입니다.

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");

이 작업의 목적은 연속된 두 공백의 모든 인스턴스를 단일 공백으로 바꾸는 것입니다.그러나 이것은 실제로 효과가 없다.

제가 정규식이나 "백지"라는 용어에 대해 심각한 오해를 하고 있는 건가요?

하면 안 요.\sUTS#18의 RL1.2를 충족하기 위해 엄격히 요구되지만, Java는 Unicode 공백 속성을 지원하지 않기 때문에 Java에서 공백 공간을 일치시킵니다.

포인트를 Unicode 26으로 합니다.\p{White_Space}그 중 한 종류입니다: 그 20 、 개 20 、 양 20 、 。\pZ General Category = Private 및 나머지 6개는 다음과 같습니다.\p{Cc} General Category=Control.

화이트 스페이스는 꽤 안정된 특성입니다.그리고 그와 같은 공간은 사실상 영원히 존재해 왔습니다.그래도 Java에는 이러한 Unicode Standard에 준거한 속성이 없기 때문에 대신 다음과 같은 코드를 사용해야 합니다.

String whitespace_chars =  ""       /* dummy empty string for homogeneity */
                        + "\\u0009" // CHARACTER TABULATION
                        + "\\u000A" // LINE FEED (LF)
                        + "\\u000B" // LINE TABULATION
                        + "\\u000C" // FORM FEED (FF)
                        + "\\u000D" // CARRIAGE RETURN (CR)
                        + "\\u0020" // SPACE
                        + "\\u0085" // NEXT LINE (NEL) 
                        + "\\u00A0" // NO-BREAK SPACE
                        + "\\u1680" // OGHAM SPACE MARK
                        + "\\u180E" // MONGOLIAN VOWEL SEPARATOR
                        + "\\u2000" // EN QUAD 
                        + "\\u2001" // EM QUAD 
                        + "\\u2002" // EN SPACE
                        + "\\u2003" // EM SPACE
                        + "\\u2004" // THREE-PER-EM SPACE
                        + "\\u2005" // FOUR-PER-EM SPACE
                        + "\\u2006" // SIX-PER-EM SPACE
                        + "\\u2007" // FIGURE SPACE
                        + "\\u2008" // PUNCTUATION SPACE
                        + "\\u2009" // THIN SPACE
                        + "\\u200A" // HAIR SPACE
                        + "\\u2028" // LINE SEPARATOR
                        + "\\u2029" // PARAGRAPH SEPARATOR
                        + "\\u202F" // NARROW NO-BREAK SPACE
                        + "\\u205F" // MEDIUM MATHEMATICAL SPACE
                        + "\\u3000" // IDEOGRAPHIC SPACE
                        ;        
/* A \s that actually works for Java’s native character set: Unicode */
String     whitespace_charclass = "["  + whitespace_chars + "]";    
/* A \S that actually works for  Java’s native character set: Unicode */
String not_whitespace_charclass = "[^" + whitespace_chars + "]";

, 그럼 에는 '어울릴 수 .whitespace_charclass + "+"★★★★★★★★★★★★★★★의 패턴으로replaceAll.


다 미안해.Java의 정규식은 네이티브 문자 집합에서는 그다지 잘 작동하지 않기 때문에, 그것들을 작동시키기 위해서는 이국적인 후프를 건너뛰어야 합니다.

봐야 .\w ★★★★★★★★★★★★★★★★★」\b드디어 제대로 행동할 수 있게 됐어!

네, 그럴 수도 있고, 정말 혼란스럽죠.그건 자비를 베푸는 거야Java용 표준 규격 regex 라이브러리를 얻는 가장 쉬운 방법은 JNI를 ICU에 연결하는 것입니다.구글이 안드로이드를 위해 하는 것은 OraSun이 따라잡지 못하기 때문이다.

그렇게 하고 싶지 않지만 Java를 계속 사용하고 싶다면, 저는 프런트 엔드 regex rewriting 라이브러리를 가지고 있습니다.Java의 패턴을 수정하고, 적어도 UTS#18 Unicode 표준 Expressions의 RL1.2a의 요건에 적합하도록 하기 위해 작성했습니다.

, 결과를 요.matcher.replaceAll():

String result = matcher.replaceAll(" ");
System.out.println(result);

Java의 경우(php, javascript, 기타 없음):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

나한테는 효과가 있는 것 같아:

String s = "  a   b      c";
System.out.println("\""  + s.replaceAll("\\s\\s", " ") + "\"");

인쇄:

" a  b   c"

코드 대신 이 작업을 수행하려고 했던 것 같습니다.

Pattern whitespace = Pattern.compile("\\s\\s");
Matcher matcher = whitespace.matcher(s);
String result = "";
if (matcher.find()) {
    result = matcher.replaceAll(" ");
}

System.out.println(result);

Regexbuddy(regex developer application) 포럼에 질문을 보냈을 때 \s Java 질문에 대한 보다 정확한 답변을 받았습니다.

메시지 작성자: Jan Goyvaerts

자바에서는 단축키 \s, \d 및 \w에는 ASCII 문자만 포함됩니다.이는 Java의 버그가 아니라 정규 표현으로 작업할 때 주의해야 할 많은 사항 중 하나입니다.줄 바꿈뿐만 아니라 모든 Unicode 공백을 일치시키려면 Java에서 [\s\p{Z}]를 사용합니다.RegexBuddy는 \p{javaSpaceChar}([\s\p{Z}]와 정확히 일치하는) 등의 Java 고유 속성을 아직 지원하지 않습니다.

입력이 ASCII 만일 경우 \s\s는 2개의 공백과 일치합니다.진짜 문제는 OP 코드에 있습니다.그 질문에서 인정된 답변이 지적하고 있습니다.

자바어 스페이스 는 유니코드 스페이스 문자를 할 수 .\p{Zs}syslog.syslog.syslog.

따라서 하나 이상의 이국적인 공간을 플레인 공간으로 대체하려면 다음과 같이 하십시오.

String txt = "whatever my string is";
String newTxt = txt.replaceAll("\\p{Zs}+", " ");

이 글을 할 것 같습니다. 만약 당신이 이 제품을 사용해본 적이 있다면trim()에서는 ( 문자열에 합니다.strip(),stripLeading() , , , , 입니다.stripTrailing()문자열로 기능합니다.그것들은 당신이 모든 종류의 뭉글뭉글한 공백 문자를 잘라내는 것을 도울 수 있다.한 것에 Java 의 「Java」를해 주세요.Character.isWhitespace()★★★★★★ 。

목적에 따라 다음 스니펫을 사용할 수 있습니다.

import org.apache.commons.lang3.StringUtils;

StringUtils.normalizeSpace(string);

이렇게 하면 간격이 싱글로 정규화되고 시작 및 후행 공백도 제거됩니다.

String sampleString = "Hello    world!";
sampleString.replaceAll("\\s{2}", " "); // replaces exactly two consecutive spaces
sampleString.replaceAll("\\s{2,}", " "); // replaces two or more consecutive white spaces
Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);

boolean flag = true;
while(flag)
{
 //Update your original search text with the result of the replace
 modLine = matcher.replaceAll(" ");
 //reset matcher to look at this "new" text
 matcher = whitespace.matcher(modLine);
 //search again ... and if no match , set flag to false to exit, else run again
 if(!matcher.find())
 {
 flag = false;
 }
}

공백 문자를 일치시키려면

Pattern whitespace = Pattern.compile("\\s", Pattern.UNICODE_CHARACTER_CLASS);

옵션은 "Unicode Technical Standard #18: Unicode 정규 표현 Annex C: Compatibility Properties"에 준거사전 정의된 문자 클래스 및 POSIX 문자 클래스의 Unicode 버전을 활성화합니다.

을 netable, netable에서도 로 할 수.(?U)의 모든 Unicode regex를 사용할 수 .

String result = text.replaceAll("(?U)\\s+", ""); // removes all whitespaces
String result = text.replaceAll("(?U)\\s", "-"); // replaces each single whitespace with -
String result = text.replaceAll("(?U)\\s+", "-"); // replaces chunks of one or more consecutive whitespaces with a single -
String result = text.replaceAll("(?U)\\G\\s", "-"); // replaces each single whitespace at the start of string with -

온라인으로 Java 데모를 참조하십시오.

String text = "\u00A0 \u00A0\tStart reading\u00A0here..."; // \u00A0 - non-breaking space
System.out.println("Text: '" + text + "'"); // => Text: '       Start reading here...'
System.out.println(text.replaceAll("(?U)\\s+", "")); // => Startreadinghere...
System.out.println(text.replaceAll("(?U)\\s", "-")); // => ----Start-reading-here...
System.out.println(text.replaceAll("(?U)\\s+", "-")); // => -Start-reading-here...
System.out.println(text.replaceAll("(?U)\\G\\s", "-")); // => ----Start reading here... 

RE에서 공백 공간을 사용하는 것은 귀찮은 일이지만, 효과가 있다고 생각합니다.OP의 문제는 StringTokenizer 또는 split() 메서드를 사용하여 해결할 수도 있습니다.단, RE를 사용하는 경우(매처가 String을 어떻게 분할하고 있는지를 표시하기 위해 println()의 코멘트를 해제하는 경우)에는, 다음의 샘플코드가 있습니다.

import java.util.regex.*;

public class Two21WS {
    private String  str = "";
    private Pattern pattern = Pattern.compile ("\\s{2,}");  // multiple spaces

    public Two21WS (String s) {
            StringBuffer sb = new StringBuffer();
            Matcher matcher = pattern.matcher (s);
            int startNext = 0;
            while (matcher.find (startNext)) {
                    if (startNext == 0)
                            sb.append (s.substring (0, matcher.start()));
                    else
                            sb.append (s.substring (startNext, matcher.start()));
                    sb.append (" ");
                    startNext = matcher.end();
                    //System.out.println ("Start, end = " + matcher.start()+", "+matcher.end() +
                    //                      ", sb: \"" + sb.toString() + "\"");
            }
            sb.append (s.substring (startNext));
            str = sb.toString();
    }

    public String toString () {
            return str;
    }

    public static void main (String[] args) {
            String tester = " a    b      cdef     gh  ij   kl";
            System.out.println ("Initial: \"" + tester + "\"");
            System.out.println ("Two21WS: \"" + new Two21WS(tester) + "\"");
}}

다음 정보를 생성합니다(javac과 컴파일하여 명령 프롬프트에서 실행).

% Java Two21WS 이니셜: "a cdef gh ij kl" 221WS: "a cdef gh ij kl"

언급URL : https://stackoverflow.com/questions/4731055/whitespace-matching-regex-java

반응형