정규식이란 ? – Java정규식 / 정규표현식 (Regular Expressions; Regex)

정규표현식은 문자열을 처리하는 방법 중의 하나로 특정한 조건의 문자를 '검색’하거나 '치환’하는 과정을 매우 간편하게 처리 할 수 있도록 하는 수단이다.

대표적인 정규표현식

표현식 설명
^ 문자열의 시작 ([]대괄호 안에서는 부정을 의미한다.)
$ 문자열의 종료
. 임의의 한 문자 (문자의 종류 가리지 않음)
* 앞 문자가 없을 수도 무한정 많을 수도 있음
+ 앞 문자가 하나 이상
? 앞 문자가 없거나 하나있음
[] 문자의 집합이나 범위를 나타내며 두 문자 사이는 - 기호로 범위를 나타낸다. []내에서 ^가 선행하여 존재하면 not 을 나타낸다.
{} 횟수 또는 범위를 나타낸다.
() 소괄호 안의 문자를 하나의 문자로 인식
| 패턴 안에서 or 연산을 수행할 때 사용
s 공백 문자
S 공백 문자가 아닌 나머지 문자
w 알파벳이나 숫자 또는 _ 포함
W 알파벳이나 숫자를 제외한 문자
d 숫자 [0-9]와 동일
D 숫자를 제외한 모든 문자
A 맨 앞을 의미한다.
A 맨 뒤를 의미한다.
“정규표현식 역슬래시()는 확장 문자
역슬래시 다음에 일반 문자가 오면 특수문자로 취급하고 역슬래시 다음에 특수문자가 오면 그 문자 자체를 의미”
(?i) 앞 부분에 (?i) 라는 옵션을 넣어주면 대소문자를 구분하지 않음

간단한 예제 분석 1 .

예제의 ^[0-9]*$ 를 분석해보면

^ 으로 우선 패턴의 시작을 알립니다.
[0-9] 괄호사이에 두 숫자를 넣어 범위를 지정해줄 수 있습니다.
* 를 넣으면 글자 수를 상관하지 않고 검사합니다.
$ 으로 패턴의 종료를 알립니다.

간단한 예제 분석 2.

  1. 숫자로 시작하는것 검색

d+(숫자로시작하는것)

  1. 문장안에서 날짜값 빼오기

2018/7/3 테스트행 크크크를 손에 넣었다.
자동차를 탄다 18년06월13일 날에
d+.d+.d+ -> 2018/7/3 , 18년06월13 잡힌다.

간단한 예제 분석3.

1
2
3
4
5
6
7
8
9
10
11

Pattern pattern = Pattern.compile("d+.d+.d+");
final Matcher matcher = pattern.matcher("2018/7/3 테스트행 크크크를 손에 넣었다. 2018/7/4");

if(matcher.find()){
final String group = matcher.group();// 2018/7/3
}

final String group = matcher.group();// 2018/7/3
matcher.find(); // find안하면 안바뀐다.
final String group = matcher.group();// 2018/7/4
  1. replace(패턴에 맞는 값을 새로운 값으로 치환)

1
2
3
4
5
6
7
8
9
10
11
public void () {
String target = "나는 2008년도에 입학했다.";
String regEx = "[0-9]";
Pattern pat = Pattern.compile(regEx);

Matcher m = pat.matcher(target);
String result = m.replaceAll("2"); // 패턴과 일치할 경우 "2"로 변경

System.out.println("출력 : " + result);
// 출력 : 나는 2222년도에 입학했다.
}

예제 1

대소문자를 구분한다.

Case 1
Regular Expression: Hello
matches: Hello, world!

Case 2
Regular Expression: hello
matches: Hello, world!

예제 2

공백, 스페이스, 탭을 고려해야한다.

Case 1
Regular Expression: Hello, world
matches: Hello, world!
Case 2
Regular Expression: Hello, world
matches: Hello, world!

예제 3

^는 시작하는 문자열에 대해서 매치를 해준다.
$는 끝나는 문자열에 대해서 매치를 해준다.
Case 1
Regular Expression: ^who
matches: who is who
Case 2
Regular Expression: who$
matches: who is who

예제 4

특수 문자 예를들어 위의 $같이 이런것에 정규 표현식을 정욕하려면 를 적용해야한다.

Case 1
Regular Expression: ^$
matches: $12$ - $25$

Case 2
Regular Expression: \$
matches: $12$ - $ 25 $

Case 3
Regular Expression: ^\$
matches: $12$ - $25$

Case 4
Regular Expression: $$
matches: $12$ - $25$

예제 5

.은 어떤 문자든 정규 표현식에 해당 된다.

Case 1
Regular Expression: .
matches: Regular expressions are powerful!!!

Case 2
아래는 . 갯수대로 문자열 그룹을 묶는다. Regular, r expr 등 처럼 문자 갯수가 6개이면 그룹으로 묶고 아니면 해당 표현식에 해당하지 않는다. 그래서 ul!!!부분은 매치에 해당되지 않는다.

Regular Expression: …
matches: Regular expressions are powerful!!!

예제 6

정규표현식에서 문자 . 을 찾는다면 를 사용해야한다.

Case 1
Regular Expression: .
matches: O.K.

Case 2
Regular Expression: ….
matches: O.K.

예제 7

[]안에 있는 문자중 하나라도 존재하면 매치가 된다.

Case 1
Regular Expression: [oyu]
matches: How do you do?

Case 2
d또는H이면서 뒤에 문자가 하나 붙어있는것
Regular Expression: [dH].
matches: How do you do?

Case 3
두개의 [][]에서 []에 들어잇는 문자열중 하나 &&(있으면서) 두번째 []에 문자열중 하나라도 있는경우
Regular Expression: [owy][yow]
matches: How do you do?

예제 8

[]대괄호 사이에 문자에 범위를 넣으면 그 범위부분을 매치 해준다. 여기에서 주의할점은 문자하나하나가 매치된다. 예를들어 a-b이면 a,b 문자하나를 의미한다.

Case 1
Regular Expression: [a-d]
matches: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789

Case 2
Regular Expression: [2-6]
matches: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789

Case 3
C~K, a~d, 2~6의 범위를 매치해준다.
Regular Expression: [C-Ka-d2-6]
matches: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789

예제 9

[] 대괄호안에서 ^를 사용한다면 그 문자는 선택되지 않을것이다.

Case 1
Regular Expression: [^CDghi45]
matches: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789
Case 2
Regular Expression: [^W-Z]
matches: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789

예제 10

소괄호로 문자들를 단어로 묶을수 있습니다. 그리고 | 를 이용하여 한문장에 여러개의 단어를 매치할 수 있습니다.

Case 1
Regular Expression: (on|ues|rida)
matches: Monday Tuesday Friday

Case 2
Regular Expression: (Mon|Tues|Fri)day
matches: Monday Tuesday Friday

Case 3
Regular Expression: …(id|esd|nd)ay
matches: Monday Tuesday Friday

예제 11

* + ?
이수량주 문자는 얼마나 앞에 많은 문자열들이 존재가능할지를 나타낸다.

Case 1

  • 을넣게되면 앞에에 문자가 있을수도있고 없을 수 도 있음
    Regular Expression: a*b
    matches: aabc abc bc acb

Case 2

  • 앞에 문자를 두면 그 앞에 문자가 반드시 하나이상있어야 매치된다.
    Regular Expression: a+b
    matches: aabc abc bc

Case 3
? 앞에 문자가 있으면 그 앞에 문자가 없거나 하나인 문자만 매치된다.
Regular Expression: a?b
matches: aabc abc bc

예제 12

*를 사용한 예제.(앞에 문자가 무한정있거나 없을 수 있음.)

Case 1 : 앞에 . 이 있으니 모든 텍스트를 매치한것이다.
Regular Expression: .

matches: [email protected] *** -- "*" -- *** [email protected]
Case 2

Regular Expression: -A*-
앞에 A가 있으니 있을수도있고 무한정 많을 수 도 있다는것을 의미한다. 아래의 문자열을 매치하면 아래와갘이 매치될것이다.
matches: [email protected] *** -- "
" -- *** [email protected]

예제 13

+를 사용한 예제.(앞에 문자가 무조건 하나 이상 있어야한다.)

Case 1
*이 앞에 하나이상 반드시 있어야한다.
Regular Expression: *+
matches: [email protected]@@- * ** - - “*” – * ** [email protected]@@-

Case 2
Regular Expression: [email protected]±
matches: [email protected]@@- * ** - - “*” – * ** [email protected]@@-

Case 3
공백을 제외하고 매치한다.
Regular Expression: [^ ]+
matches: [email protected]@@- * ** - - “*” – * ** [email protected]@@-

예제 14

?를 사용한 예제(앞문자가 하나거있거나 없음.)
Case 1
Regular Expression: -X?XX?X
matches: --XX[email protected]-XX[email protected]@-XX[email protected]@@-XX[email protected]@@@-XX[email protected]@[email protected]@-
Case 2
Regular Expression: [email protected][email protected][email protected]?-

matches: --XX[email protected]XX[email protected]@-XX[email protected]@@-[email protected]@@@-XX[email protected]@-@@-
Case 3
@가맨뒤에 있으면서 앞에@가 있을수도있고 없을 수 도 있으면서 앞에는@아니면 매치된다.
Regular Expression: [^@]@[email protected]
matches: --XX[email protected]-XX[email protected]@-XX[email protected]@@-XX[email protected]@@@-XX[email protected]@ [email protected]@-

예제 15

{} 중괄호안에 숫자들을 통해 매치해준다. 예를들어 {3} 이면 3글자씩, {3,5} 이면 3이상 5이하인 숫자를, {3,} 3글자이상을 의미한다.

Case 1
Regular Expression: .{5}
matches: One r ing t o bri ng th em al l and in t he da rknes s bin d them
Case 2
Regular Expression: [els]{1,3}
matches: One ring to bring them all and in the darkness bind them
Case 3
Regular Expression: [a-z]{3,}
matches: One ring to bring them all and in the darkness bind them

예제 16

Case 1
Regular Expression: AB*A
matches: AA ABA ABBBBA ABBCBA
Case 2
Regular Expression: AB{0,}A
matches: AA ABA ABBBBA ABBCBA
Case 3
Regular Expression: AB+A
matches: AA ABA ABBBBA ABBCBA
Case 4
Regular Expression: AB{1,}A
matches: AA ABA ABBBBA ABBCBA
Case 5
Regular Expression: AB?A
matches: AA ABA ABBBBA ABBCBA
Case 6
Regular Expression: AB{0,1}A
matches: AA ABA ABBBBA ABBCBA

예제 17

Case 1
Regular Expression: r.*
matches: One ring to bring them all and in the darkness bind them
Case 2
아래 같은경우 ?앞에 * 수량자가 나왔다. 원래 문자가 와야하는데 * 수량자가 왔다. 이렇게되면 앞에 * 수량자의 의미는 0으로 바뀐다. * 원래 의미가 0개 아니면 1개 혹은 그이상을 의미한다. ?가 앞에 오게되면 처음의미인 0을 의미한다. 그렇기 때문에 앞에 .*은 0개를 의미한다.
Regular Expression: r.*?
matches: One ring to bring them all and in the darkness bind them
Case 3
Regular Expression: r.+
matches: One ring to bring them all and in the darkness bind them
Case 4
여기에서도 ?앞에 수량자가 나왔다. +는 1혹은 그이상의 단어를 의미하기 떄문에 첫 의미인 1을 가져와 r그리고 어떤 문자가 반드시 하나 있어야하면서
Regular Expression: r.+?
matches: One ring to bring them all and in the darkness bind them
Case 5
Regular Expression: r.?
matches: One ring to bring them all and in the darkness bind them
Case 6
밑에서도 ?앞에 ? 가있는데 ?는 0아니면 1을의미하기때문에 앞에 의미인 0이 들어가 r만 매치된다.
Regular Expression: r.??
matches: One ring to bring them all and in the darkness bind them

Case 7
Resgular Expression : <div>.+
matches:<div>test<div><div>test<div>
Resgular Expression : <div>.+?</div>
matches:<div>test<div>

test<div>

예제 18

w는 모든 문자(’_’)를 매치해준다. 단 특수문자는 제외한다.

Case 1
Regular Expression: w
matches: A 1 B 2 c 3 d _ 4 e : 5 f f G G 7 7_ _
Case 2
Regular Expression: w+
matches: A1 B2 c3 d_4 e:5 ffGG77__
Case 3
Regular Expression: [a-z]w*
matches: A1 B2 c3 d_4 e:5 ffGG77
Case 4
Regular Expression: w{5}
matches: A1 B2 c3 d_4 e:5 ffGG77–

Case 5
Regular Expression: [A-z0-9_]
matches: A 1 B 2 c 3 d _ 4 e : 5 f f G G 7 7_ _

예제 19

?=문자를 제외하고 그앞에 선택한 문자들이 매치된다.

Case 1
Regular Expression: w+(?=X)
matches: AAAX—aaax—111
Case 2
Regular Expression: w+(?=w)
matches: AAAX—aaax—111

참고