Java에서 정규 표현식을 환영합니다. Java에서는 Regex라고도 불립니다. 프로그래밍을 시작할 때, Java 정규 표현식은 정말 악몽이었습니다. 이 자습서는 Java에서 정규 표현식을 마스터하는 데 도움이 되도록 목표로 합니다. 나는 또한 Java Regex 학습을 되새기기 위해 여기로 돌아올 것입니다.
Java에서 정규 표현식
Java에서의 정규 표현식은 문자열에 대한 패턴을 정의합니다. 정규 표현식은 텍스트를 검색, 편집 또는 조작하는 데 사용될 수 있습니다. 정규 표현식은 언어별로 다르지만, Java에서의 정규 표현식은 Perl과 가장 유사합니다. Java Regex 클래스는
java.util.regex
패키지에 존재하며, 세 가지 클래스를 포함합니다:
- Pattern:
Pattern
객체는 정규 표현식의 컴파일된 버전입니다. Pattern 클래스는 공개 생성자가 없으며, 정규 표현식 인수를 전달하여 패턴 객체를 생성하기 위해 공개 정적 메서드compile
을 사용합니다. - Matcher:
Matcher
는 입력 문자열 패턴을 생성된 패턴 객체와 일치시키는 자바 정규식 엔진 객체입니다. Matcher 클래스에는 공개 생성자가 없으며 입력 문자열을 인수로 사용하는 패턴 객체matcher
메서드를 사용하여 Matcher 객체를 얻습니다. 그런 다음 입력 문자열이 정규식 패턴과 일치하는지 여부에 따라 boolean 결과를 반환하는matches
메서드를 사용합니다. - PatternSyntaxException:
PatternSyntaxException
은 정규 표현식 구문이 올바르지 않은 경우 throw됩니다.
자바 정규식 예제 프로그램을 살펴보겠습니다.
package com.journaldev.util;
import java.util.regex.*;
public class PatternExample {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(".xx.");
Matcher matcher = pattern.matcher("MxxY");
System.out.println("Input String matches regex - "+matcher.matches());
// 잘못된 정규식
pattern = Pattern.compile("*xx*");
}
}
이 자바 정규식 예제 프로그램을 실행하면 다음과 같은 출력이 나옵니다.
Input String matches regex - true
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*xx*
^
at java.util.regex.Pattern.error(Pattern.java:1924)
at java.util.regex.Pattern.sequence(Pattern.java:2090)
at java.util.regex.Pattern.expr(Pattern.java:1964)
at java.util.regex.Pattern.compile(Pattern.java:1665)
at java.util.regex.Pattern.(Pattern.java:1337)
at java.util.regex.Pattern.compile(Pattern.java:1022)
at com.journaldev.util.PatternExample.main(PatternExample.java:13)
자바 정규식은 문자열을 중심으로 하므로 Java 1.4에서는 matches
메서드를 제공하기 위해 String 클래스가 확장되었습니다. 내부적으로는 처리를 수행하기 위해 Pattern
및 Matcher
자바 정규식 클래스를 사용하지만 코드 줄을 줄일 수 있습니다. Pattern
클래스에는 regex와 입력 문자열을 인수로 사용하여 일치하는 boolean 결과를 반환하는 matches
메서드도 포함되어 있습니다. 따라서 아래 코드는 Java에서 정규식을 사용하여 입력 문자열을 일치시키는 데 잘 작동합니다.
String str = "bbb";
System.out.println("Using String matches method: "+str.matches(".bb"));
System.out.println("Using Pattern matches method: "+Pattern.matches(".bb", str));
그래서 입력 문자열이 패턴과 일치하는지 확인하는 것이 요구 사항이라면, 단순한 문자열 일치 방법을 사용하여 시간과 코드 라인을 절약해야합니다. 입력 문자열을 조작해야하거나 패턴을 재사용해야하는 경우에만 Pattern 및 Matches 클래스를 사용해야합니다. 정규식으로 정의된 패턴은 문자열의 왼쪽에서 오른쪽으로 적용되며 소스 문자가 일치에 사용되면 재사용 할 수 없습니다. 예를 들어, 정규식 “121”은 “31212142121”을 “_121____121″로만 두 번 일치합니다.
자바 정규식 – 일반 일치 기호
Regular Expression | Description | Example |
---|---|---|
. | Matches any single character | (“…”, “a%”) – true(“…”, “.a”) – true (“…”, “a”) – false |
^aaa | Matches aaa regex at the beginning of the line | (“^a.c.”, “abcd”) – true (“^a”, “ac”) – false |
aaa$ | Matches regex aaa at the end of the line | (“…cd$”, “abcd”) – true(“a$”, “a”) – true (“a$”, “aca”) – false |
[abc] | Can match any of the letter a, b or c. [] are known as character classes. | (“^[abc]d.”, “ad9”) – true(“[ab].d$”, “bad”) – true (“[ab]x”, “cx”) – false |
[abc][12] | Can match a, b or c followed by 1 or 2 | (“[ab][12].”, “a2#”) – true(“[ab]…[12]”, “acd2”) – true (“[ab][12]”, “c2”) – false |
[^abc] | When ^ is the first character in [], it negates the pattern, matches anything except a, b or c | (“[^ab][^12].”, “c3#”) – true(“[^ab]…[^12]”, “xcd3”) – true (“[^ab][^12]”, “c2”) – false |
[a-e1-8] | Matches ranges between a to e or 1 to 8 | (“[a-e1-3].”, “d#”) – true(“[a-e1-3]”, “2”) – true (“[a-e1-3]”, “f2”) – false |
xx | yy | Matches regex xx or yy |
자바 정규식 메타 문자
우리는 Java 정규식에 일부 메타 문자가 있습니다. 이것은 일반적인 일치 패턴에 대한 단축키와 같습니다.
Regular Expression | Description |
---|---|
\d | Any digits, short of [0-9] |
\D | Any non-digit, short for [^0-9] |
\s | Any whitespace character, short for [\t\n\x0B\f\r] |
\S | Any non-whitespace character, short for [^\s] |
\w | Any word character, short for [a-zA-Z_0-9] |
\W | Any non-word character, short for [^\w] |
\b | A word boundary |
\B | A non word boundary |
정규 표현식에서 메타 문자를 일반 문자로 사용하는 두 가지 방법이 있습니다.
- 메타 문자 앞에 백 슬래시 (\)를 붙입니다.
- \Q (인용문을 시작하는)과 \E (그것을 종료하는) 내에서 메타 문자를 유지합니다.
자바에서의 정규 표현식 – 양자화자
자바 정규 표현식 양자화자는 일치해야 하는 문자의 발생 횟수를 지정합니다.
Regular Expression | Description |
---|---|
x? | x occurs once or not at all |
X* | X occurs zero or more times |
X+ | X occurs one or more times |
X{n} | X occurs exactly n times |
X{n,} | X occurs n or more times |
X{n,m} | X occurs at least n times but not more than m times |
자바 정규 표현식 양자화자는 문자 클래스 및 캡처 그룹과 함께 사용할 수도 있습니다. 예를 들어, [abc]+는 a, b 또는 c가 한 번 이상 나타남을 의미합니다. (abc)+는 그룹 “abc”가 한 번 이상 나타남을 의미합니다. 이제 캡처 그룹에 대해 알아보겠습니다.
자바에서의 정규 표현식 – 캡처 그룹
자바에서의 정규 표현식 캡처 그룹은 여러 문자를 단일 단위로 처리하는 데 사용됩니다. ()
를 사용하여 그룹을 만들 수 있습니다. 캡처 그룹과 일치하는 입력 문자열의 일부는 메모리에 저장되어 백레퍼런스를 사용하여 호출할 수 있습니다. 자바 정규 표현식 패턴에서 캡처 그룹의 수를 찾으려면 matcher.groupCount
메서드를 사용할 수 있습니다. 예를 들어, ((a)(bc))에는 3개의 캡처 그룹이 포함되어 있습니다 – ((a)(bc)), (a) 및 (bc) . 캡처 그룹과 백레퍼런스는 혼란스러울 수 있으므로 예제를 통해 이해해 봅시다.
System.out.println(Pattern.matches("(\\w\\d)\\1", "a2a2")); //true
System.out.println(Pattern.matches("(\\w\\d)\\1", "a2b2")); //false
System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B2AB")); //true
System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B3AB")); //false
첫 번째 예에서 실행 시간에 첫 번째 캡처 그룹은 (\w\d)이며 입력 문자열 “a2a2″와 일치할 때 “a2″로 평가되어 기억에 저장됩니다. 따라서 \1은 “a2″를 가리키며 따라서 true를 반환합니다. 동일한 이유로 두 번째 문장은 false를 출력합니다. 문장 3과 4에 대한 이 시나리오를 이해해 보세요. 🙂 이제 Pattern 및 Matcher 클래스의 중요한 메서드 몇 가지를 살펴보겠습니다.
- 플래그와 함께 Pattern 객체를 생성할 수 있습니다. 예를 들어
Pattern.CASE_INSENSITIVE
는 대소문자를 구분하지 않는 매칭을 가능하게 합니다. - Pattern 클래스는 또한 String 클래스
split()
메서드와 유사한split(String)
메서드를 제공합니다. - Pattern 클래스의
toString()
메서드는 이 패턴이 컴파일된 정규식 문자열을 반환합니다. - Matcher 클래스에는 일치 항목이 입력 문자열에서 정확히 어디에서 발견되었는지를 보여주는
start()
및end()
인덱스 메서드가 있습니다. - Matcher 클래스는 또한 String 조작 메서드
replaceAll(String replacement)
및replaceFirst(String replacement)
를 제공합니다.
이러한 자바 정규식 메서드를 간단한 예제 프로그램에서 살펴보겠습니다.
package com.journaldev.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExamples {
public static void main(String[] args) {
// 플래그와 함께 패턴 사용
Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("ABcabdAb");
// Matcher find(), group(), start(), end() 메서드 사용
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " index and ending at index " + matcher.end());
}
// Pattern split() 메서드 사용
pattern = Pattern.compile("\\W");
String[] words = pattern.split("one@two#three:four$five");
for (String s : words) {
System.out.println("Split using Pattern.split(): " + s);
}
// Matcher.replaceFirst() 및 replaceAll() 메서드 사용
pattern = Pattern.compile("1*2");
matcher = pattern.matcher("11234512678");
System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
}
}
위의 자바 정규식 예제 프로그램의 출력은 다음과 같습니다.
Found the text "AB" starting at 0 index and ending at index 2
Found the text "ab" starting at 3 index and ending at index 5
Found the text "Ab" starting at 6 index and ending at index 8
Split using Pattern.split(): one
Split using Pattern.split(): two
Split using Pattern.split(): three
Split using Pattern.split(): four
Split using Pattern.split(): five
Using replaceAll: _345_678
Using replaceFirst: _34512678
그것은 모두 자바에서 정규 표현식에 대한 것입니다. 자바 정규식은 처음에는 어렵게 느껴질 수 있지만, 시간을 들여서 작업하면 쉽게 배우고 사용할 수 있습니다.
완전한 코드와 더 많은 정규 표현식 예제를 확인할 수 있습니다. 저희의 GitHub 저장소에서.
Source:
https://www.digitalocean.com/community/tutorials/regular-expression-in-java-regex-example