UFO ET IT

Java의 원시 문자열-특히 정규식 용

ufoet 2020. 11. 7. 18:14
반응형

Java의 원시 문자열-특히 정규식 용


Java에서 이스케이프 시퀀스없이 원시 문자열을 사용하는 방법이 있습니까?

(나는 상당한 양의 정규식 코드를 작성하고 있으며 원시 문자열은 내 코드를 훨씬 더 읽기 쉽게 만들 것입니다)

나는 언어가 이것을 직접 제공하지 않는다는 것을 이해합니다. 그러나 어떤 식 으로든 그것들을 "시뮬레이션"할 수있는 방법이 있습니까?


아니, 없습니다.

일반적으로 속성 파일에 원시 문자열과 정규식을 넣지 만 이스케이프 시퀀스 요구 사항도 있습니다.


이클립스를 사용하는 경우 해결 방법입니다. 문자열 리터럴에 텍스트를 붙여 넣을 때 자동으로 긴 텍스트 블록을 올바르게 여러 줄로 표시하고 특수 문자를 자동으로 이스케이프 할 수 있습니다.

"-여기에 붙여 넣기-";

window → preferences → java → Editor → Typing → "문자열 리터럴에 붙여 넣을 때 텍스트 이스케이프" 에서 해당 옵션을 활성화하면


나는 Pattern.quote를 사용 합니다. 그리고 그것은 질문의 문제를 해결합니다. 따라서 :

Pattern pattern = Pattern.compile(Pattern.quote("\r\n?|\n"));

quote 메서드는 제공된 문자열 인수와 일치하는 문자열을 반환합니다. 반환 문자열은 우리 사례에 대해 적절하게 인용 된 문자열입니다.


아니요 (아주 슬프게도).


클래스 경로에 원시 텍스트 파일이 있고 getResourceAsStream (....)으로 읽습니다.


( 속성 파일 은 일반적이지만 지저분합니다. 대부분의 정규식을 코드로 취급하고 참조 할 수있는 곳에 보관합니다. 실제 질문은 다음과 같습니다.)

예, 가독성이 떨어지는 것을 피할 수있는 방법이 있습니다. 시도해 볼 수 있습니다.

String s = "crazy escaped garbage"; //readable version//

업데이트 할 때주의가 필요합니다. Eclipse에는 따옴표 사이에 텍스트를 붙여 넣을 수있는 옵션이 있으며 이스케이프 시퀀스가 ​​적용됩니다. 전술은 먼저 읽을 수있는 버전을 편집 한 다음 쓰레기를 삭제하고 빈 따옴표 ""사이에 붙여 넣는 것입니다.


아이디어 시간 :

편집자를 해킹하여 변환하십시오. 플러그인으로 출시됩니다. 플러그인을 확인했지만 아무것도 찾지 못했습니다 (검색 시도). 이스케이프 된 소스 문자열과 텍스트 상자 텍스트 사이에는 일대일 대응이 있습니다 (\ n, \ r \ n 할인). 끝에 두 개의 따옴표가있는 강조 표시된 텍스트를 사용할 수 있습니다.

String s = "##########
#####";

여기서 #은 강조 표시된 문자입니다. 줄 바꿈은 줄 바꿈으로 처리됩니다. 강조 표시된 영역 내에 입력하거나 붙여 넣은 텍스트는 '실제'소스에서 이스케이프 처리되고 그렇지 않은 것처럼 표시됩니다. (Eclipse가 붙여 넣은 텍스트를 이스케이프하는 것과 같은 방식으로 입력 된 텍스트를 이스케이프하고 백 슬래시없이 표시합니다.) 정상적으로 편집하려면 따옴표 중 하나를 삭제하여 구문 오류를 발생시킵니다. 흠.


참고 : 오늘부터 사용할 수 없습니다. 아마도 기능이 출시 될 때 마다이 답변을 다시 편집 할 것입니다.

Java에서 원시 문자열을 도입하기위한 제안이 진행 중 입니다. 정규식의 경우 실제로 매우 유용합니다.

예 1 : 다음과 같이 코딩 된 정규식 문자열

  System.out.println("this".matches("\\w\\w\\w\\w"));

다음과 같이 번갈아 코딩 될 수 있습니다.

System.out.println("this".matches(`\w\w\w\w`));

백 슬래시는 특별한 의미가있는 것으로 해석되지 않기 때문입니다.

예 2 : 외국어가있는 여러 줄의 문자열 리터럴이 추가됩니다.

A multiple line string that was coded as 
    String html = "<html>\n" +
                "    <body>\n" +
                "         <p>Hello World.</p>\n" +
                "    </body>\n" +
                "</html>\n";

다음과 같이 번갈아 코딩 될 수 있습니다.

 String html = `<html>
                       <body>
                           <p>Hello World.</p>
                       </body>
                   </html>
                  `;

중간 따옴표, 연결 및 명시 적 줄 바꿈이 필요하지 않습니다.

곧 출시 될 예정입니다.


String # getBytes () 는 실제로 16 비트 UTF-16으로 인코딩 된 문자열을 포함하는 모든 단일 String 객체에 포함 된 내부 바이트 배열의 복사본을 노출합니다. 바이트 배열에는 플랫폼의 기본 문자 집합과 일치하도록 변환 된 동일한 문자열이 포함됩니다. 내가 말하는 것은 이것이 자바에서 얻을 수있는 "원시"문자열에 가깝다고 생각한다는 것입니다.


이스케이프되지 않은 고유 한 속성 판독기를 작성하고 문자열을 리소스 파일에 넣을 수 있습니다.


I personally consider regex strings data and not code, so I don't like them in my code--but I realize that's impractical and unpopular (Yes, I realize it, you don't have to yell at me).

Given that there is no native way to do this, I can come up with two possibilities (well, three but the third is, umm, unnatural).

So my personal preference would be to just parse a file into strings. You could name each entry in the file and load them all into a hash table for easy access from your code.

Second choice, create a file that will be pre-processed into a java interface; it could escape the regex as it does so. Personally I hate code generation, but if the java file is 100% never human edited, it's not too bad (the real evil is generated files that you are expected to edit!)

Third (tricky and probably a bad idea): You might be able to create a custom doclet that will extract strings from your comments into a text file or a header file at compile time, then use one of the other two methods above. This keeps your strings in the same file in which they are being used. This could be really hard to do correctly, and the penalties of failure are extreme, so I wouldn't even consider it unless I had an overwhelming need and some pretty impressive talent.

I only suggest this because comments are free-form and things within a "pre" tag are pretty safe from formatters and other system uglies. The doclet could extract this before printing the javadocs, and could even add some of the generated javadocs indicating your use of regex strings.

Before downvoting and telling me this is a stupid idea--I KNOW, I just thought I'd suggest it because it's interesting, but my preference as I stated above is a simple text file...


No. But there's an IntelliJ plug-in that makes this easier to deal with, called String Manipulation.

IntelliJ will also automatically escape a string pasted into it. (As @Dread points out, Eclipse has a plug-in to enable this.)

참고URL : https://stackoverflow.com/questions/1256667/raw-strings-in-java-for-regex-in-particular

반응형