이론적으로는 오토마타이론과 관련이 있다.
자바 정규식은 perl이랑 비슷한 계열. 언어마다 구현이 달라 호환성에 유의.다시말해서 자바에서 작동한 정규표현식이 다른 플랫폼이나 언어에서도 작동할거라 생각하면 안됨.
내 프로젝트에서의 적용
글 등록할 때, 글 제목을 slug로 쓰기 위해서 함수 toSlug()를 하나 만들려고 했고, "-"을 글의 제목 빈칸마다 삽입하려면 정규표현식이 필요했음. String.replaceAll(regex,replacement);
ex) regex = [\&|[\uFE30-\uFFA0]|\’|\”|\s\?\,\.]+
간단히 설명하면 1.&
2.uFE30에서 uFFA0까지
3. '
4."
5.\s(\s는 공백문자를 의미하는 메타문자이다. )
6.?
7.,
8..
1번에서 8번까지의 문자들이 오면 매칭이 성공한 것이다.
메타문자가 '+'가 있으면 1개이상 연속은 하나로 친다.
관련패키지
java.util.regex
예제
regex패키지에서 가장 많이 쓰이는 함수가 matcher,compile,quote이다.
matcher(),compile()
1.regex에 String literal만 들어간경우
@Test
public void givenText_whenSimpleRegexMatches_thenCorrect() {
Pattern pattern = Pattern.compile("foo");
Matcher matcher = pattern.matcher("foo");
assertTrue(matcher.find());
}
matcher내부적으로는 compile()이 되어있는지 확인해서 안되어있으면 thread-safe하게 컴파일한다.
public Matcher matcher(CharSequence input) {
if (!compiled) {
synchronized(this) {
if (!compiled)
compile();
}
}
Matcher m = new Matcher(this, input);
return m;
}
compile()의 역할은 excape문자들(\)을 없애주는 것이다. ex)"\\dfef\\fef" -> 컴파일을 거치면 "\dfef\fef"가 된다.
2.regex에 메타문자가 들어간 경우
<([{\^-=$!|]})?*+.>
quote()
Returns a literal pattern String for the specified String.
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
Metacharacters or escape sequences in the input sequence will be given no special meaning.
Params:
s – The string to be literalized
Returns:
A literal string replacement
Since:
1.5
public static String quote(String s) {
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E";
int lenHint = s.length();
lenHint = (lenHint < Integer.MAX_VALUE - 8 - lenHint) ?
(lenHint << 1) : (Integer.MAX_VALUE - 8);
StringBuilder sb = new StringBuilder(lenHint);
sb.append("\\Q");
int current = 0;
do {
sb.append(s, current, slashEIndex)
.append("\\E\\\\E\\Q");
current = slashEIndex + 2;
} while ((slashEIndex = s.indexOf("\\E", current)) != -1);
return sb.append(s, current, s.length())
.append("\\E")
.toString();
}
\Q와 \E 모두 escape문자이다. String a = "example"에서 쌍따옴표들은 escape하는 역할을 한다.
\Q는 \E까지 다음의 모든 문자 주변에 인용 부호를 지정합니다.
\E는 \Q ... \E 인용 시퀀스를 종료합니다.
이게 왜 쓰는지 싶겠지만 메타문자를 직접 매칭하고 싶을때 유용하게 사용할 수 있다. 다음과 같이 말이다.
System.out.println("foo".matches(".*")); // true
System.out.println("foo".matches(Pattern.quote(".*"))); // false
System.out.println(".*".matches(Pattern.quote(".*"))); // true
참고 사이트
regex101.com
A Guide To Java Regular Expressions API | Baeldung
[Java] 정규식 문법 정리(Regex) :: 그냥 그냥 블로그 (tistory.com)
java - What is the use of Pattern.quote method? - Stack Overflow
'프로그래밍 언어(must-have skills) > JAVA' 카테고리의 다른 글
@vaild에 관하여 (0) | 2022.12.28 |
---|---|
if/else문과 swich문의 성능 비교 . (0) | 2022.05.31 |
log4j취약점 패치 (0) | 2021.12.13 |
[자바]Collections.emptyMap() vs new HashMap() (0) | 2021.10.01 |
Garbage Collection (0) | 2021.09.08 |