자바 정규식
정규 표현식이란 무엇입니까?
정규식은 검색 패턴을 형성하는 일련의 문자입니다. 텍스트에서 데이터를 검색할 때 이 검색 패턴을 사용하여 검색하는 내용을 설명할 수 있습니다.
정규식은 단일 문자이거나 더 복잡한 패턴일 수 있습니다.
정규식은 모든 유형의 텍스트 검색 및 텍스트 바꾸기 작업을 수행하는 데 사용할 수 있습니다.
Java에는 내장된 정규식 클래스가 없지만 정규식 java.util.regex
과 함께 작동하도록 패키지를 가져올 수 있습니다. 패키지에는 다음 클래스가 포함됩니다.
Pattern
클래스 - 패턴 정의(검색에 사용)Matcher
클래스 - 패턴 검색에 사용PatternSyntaxException
클래스 - 정규식 패턴의 구문 오류를 나타냅니다.
예시
문장에 "w3schools"라는 단어가 있는지 확인하십시오.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
// Outputs Match found
예시 설명
이 예에서는 "w3schools"라는 단어가 문장에서 검색됩니다.
Pattern.compile()
먼저 메서드 를 사용하여 패턴을 만듭니다. 첫 번째 매개변수는 검색 중인 패턴을 나타내고 두 번째 매개변수에는 검색에서 대소문자를 구분하지 않아야 함을 나타내는 플래그가 있습니다. 두 번째 매개변수는 선택 사항입니다.
이 matcher()
메서드는 문자열에서 패턴을 검색하는 데 사용됩니다. 수행된 검색에 대한 정보가 포함된 Matcher 개체를 반환합니다.
이 find()
메서드는 문자열에서 패턴을 찾으면 true를 반환하고 찾지 못하면 false를 반환합니다.
깃발
메서드 의 플래그 compile()
는 검색이 수행되는 방식을 변경합니다. 다음은 그 중 몇 가지입니다.
Pattern.CASE_INSENSITIVE
- 검색시 대소문자는 무시됩니다.Pattern.LITERAL
- 패턴의 특수문자는 특별한 의미가 없으며 검색시 일반문자로 처리됩니다.Pattern.UNICODE_CASE
- 플래그와 함께 사용하여CASE_INSENSITIVE
영문자 이외의 문자도 무시
정규 표현식 패턴
메소드 의 첫 번째 매개변수는 Pattern.compile()
패턴입니다. 검색되는 내용을 설명합니다.
대괄호는 문자 범위를 찾는 데 사용됩니다.
Expression | Description |
---|---|
[abc] | Find one character from the options between the brackets |
[^abc] | Find one character NOT between the brackets |
[0-9] | Find one character from the range 0 to 9 |
메타 문자
메타 문자는 특별한 의미를 가진 문자입니다.
Metacharacter | Description |
---|---|
| | Find a match for any one of the patterns separated by | as in: cat|dog|fish |
. | Find just one instance of any character |
^ | Finds a match as the beginning of a string as in: ^Hello |
$ | Finds a match at the end of the string as in: World$ |
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
수량자
수량자는 수량을 정의합니다.
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
n{x} | Matches any string that contains a sequence of X n's |
n{x,y} | Matches any string that contains a sequence of X to Y n's |
n{x,} | Matches any string that contains a sequence of at least X n's |
참고: 표현식에서 특수 문자 중 하나를 검색해야 하는 경우 백슬래시( \ )를 사용하여 특수 문자를 이스케이프할 수 있습니다. Java에서 문자열의 백슬래시는 자체적으로 이스케이프되어야 하므로 특수 문자를 이스케이프하려면 두 개의 백슬래시가 필요합니다. 예를 들어, 하나 이상의 물음표를 검색하려면 "\\?" 표현식을 사용할 수 있습니다.