sitelink1 | |
---|---|
sitelink2 | |
sitelink3 | http://1 |
sitelink4 | http://ko |
sitelink5 | http://blog.naver.com/maru0226?Redirect=...0006922656 |
sitelink6 | http://sitelink1 |
Example Regex Scenarios
아래 코드는 J2SE 1.4 도큐먼트의 예제를 완성한 것이다.
/*
* 이 코드는 "One dog, two dogs in the yard." 라는 문자열을
* 표준 출력을 통해 출력한다.
*/
import java.util.regex.*;
public class Replacement {
public static void main(String[] args) throws Exception {
// ‘cat’이라는 패턴 생성
Pattern p = Pattern.compile("cat");
// 입력 문자열과 함께 매쳐 클래스 생성
Matcher m = p.matcher("one cat," + " two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// 패턴과 일치하는 문자열을 ‘dog’으로 교체해가며
// 새로운 문자열을 만든다.
while(result) {
m.appendReplacement(sb, "dog");
result = m.find();
}
// 나머지 부분을 새로운 문자열 끝에 덫붙인다.
m.appendTail(sb);
System.out.println(sb.toString());
}
}
메일 주소 포맷 확인
다음 코드는 주어진 입력 시퀀스가 메일 주소 포맷인가를 판단한다. 이 코드는 가능한 모든 형태의 메일 주소를 확인하는 것은 아니니 필요하면 코드를 더 추가해 사용하자.
/*
* 메일 주소에서 잘못된 문자 검사
*/
public class EmailValidation {
public static void main(String[] args) throws Exception {
String input = "@sun.com";
//메일 주소가 ‘.’이나 ‘@’와 같은 잘못된 문자로 시작하는 지 확인
Pattern p = Pattern.compile("^.|^@");
Matcher m = p.matcher(input);
if (m.find())
System.err.println("Email addresses don't start" + " with dots or @ signs.");
//’www.’으로 시작하는 주소를 찾는다.
p = Pattern.compile("^www.");
m = p.matcher(input);
if (m.find()) {
System.out.println("Email addresses don't start" + " with "www.", only web pages do.");
}
p = Pattern.compile("[^A-Za-z0-9.@_-~#]+");
m = p.matcher(input);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
boolean deletedIllegalChars = false;
while(result) {
deletedIllegalChars = true;
m.appendReplacement(sb, "");
result = m.find();
}
m.appendTail(sb);
input = sb.toString();
if (deletedIllegalChars) {
System.out.println("It contained incorrect characters" + " , such as spaces or commas.");
}
}
}
파일에서 제어 문자 제거
/*
* 지정된 파일에서 제어 문제를 찾아 제거한다.
*/
import java.util.regex.*;
import java.io.*;
public class Control {
public static void main(String[] args) throws Exception {
//파일 객체 생성
File fin = new File("fileName1");
File fout = new File("fileName2");
//입출력 스트림 생성
FileInputStream fis = new FileInputStream(fin);
FileOutputStream fos = new FileOutputStream(fout);
BufferedReader in = new BufferedReader (new InputStreamReader(fis));
BufferedWriter out = new BufferedWriter (new OutputStreamWriter(fos));
// 제어문자를 의미하는 패턴 생성
Pattern p = Pattern.compile("{cntrl}");
Matcher m = p.matcher("");
String aLine = null;
while((aLine = in.readLine()) != null) {
m.reset(aLine);
//제어 문자들을 빈 문자열로 대체
String result = m.replaceAll("");
out.write(result);
out.newLine();
}
in.close();
out.close();
}
}
파일 검색
/*
* .java 파일에서 주석을 찾아 출력한다.
*/
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
public class CharBufferExample {
public static void main(String[] args) throws Exception {
// 주석을 나타내는 패턴 생성
Pattern p = Pattern.compile("//.*$", Pattern.MULTILINE);
// 소스파일
File f = new File("Replacement.java");
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
// 소스 파일로부터 CharBuffer 생성
ByteBuffer bb = fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
Charset cs = Charset.forName("8859_1");
CharsetDecoder cd = cs.newDecoder();
CharBuffer cb = cd.decode(bb);
// 매칭 작업 수행
Matcher m = p.matcher(cb);
while (m.find())
System.out.println("Found comment: "+m.group());
}
}
아래 코드는 J2SE 1.4 도큐먼트의 예제를 완성한 것이다.
/*
* 이 코드는 "One dog, two dogs in the yard." 라는 문자열을
* 표준 출력을 통해 출력한다.
*/
import java.util.regex.*;
public class Replacement {
public static void main(String[] args) throws Exception {
// ‘cat’이라는 패턴 생성
Pattern p = Pattern.compile("cat");
// 입력 문자열과 함께 매쳐 클래스 생성
Matcher m = p.matcher("one cat," + " two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// 패턴과 일치하는 문자열을 ‘dog’으로 교체해가며
// 새로운 문자열을 만든다.
while(result) {
m.appendReplacement(sb, "dog");
result = m.find();
}
// 나머지 부분을 새로운 문자열 끝에 덫붙인다.
m.appendTail(sb);
System.out.println(sb.toString());
}
}
메일 주소 포맷 확인
다음 코드는 주어진 입력 시퀀스가 메일 주소 포맷인가를 판단한다. 이 코드는 가능한 모든 형태의 메일 주소를 확인하는 것은 아니니 필요하면 코드를 더 추가해 사용하자.
/*
* 메일 주소에서 잘못된 문자 검사
*/
public class EmailValidation {
public static void main(String[] args) throws Exception {
String input = "@sun.com";
//메일 주소가 ‘.’이나 ‘@’와 같은 잘못된 문자로 시작하는 지 확인
Pattern p = Pattern.compile("^.|^@");
Matcher m = p.matcher(input);
if (m.find())
System.err.println("Email addresses don't start" + " with dots or @ signs.");
//’www.’으로 시작하는 주소를 찾는다.
p = Pattern.compile("^www.");
m = p.matcher(input);
if (m.find()) {
System.out.println("Email addresses don't start" + " with "www.", only web pages do.");
}
p = Pattern.compile("[^A-Za-z0-9.@_-~#]+");
m = p.matcher(input);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
boolean deletedIllegalChars = false;
while(result) {
deletedIllegalChars = true;
m.appendReplacement(sb, "");
result = m.find();
}
m.appendTail(sb);
input = sb.toString();
if (deletedIllegalChars) {
System.out.println("It contained incorrect characters" + " , such as spaces or commas.");
}
}
}
파일에서 제어 문자 제거
/*
* 지정된 파일에서 제어 문제를 찾아 제거한다.
*/
import java.util.regex.*;
import java.io.*;
public class Control {
public static void main(String[] args) throws Exception {
//파일 객체 생성
File fin = new File("fileName1");
File fout = new File("fileName2");
//입출력 스트림 생성
FileInputStream fis = new FileInputStream(fin);
FileOutputStream fos = new FileOutputStream(fout);
BufferedReader in = new BufferedReader (new InputStreamReader(fis));
BufferedWriter out = new BufferedWriter (new OutputStreamWriter(fos));
// 제어문자를 의미하는 패턴 생성
Pattern p = Pattern.compile("{cntrl}");
Matcher m = p.matcher("");
String aLine = null;
while((aLine = in.readLine()) != null) {
m.reset(aLine);
//제어 문자들을 빈 문자열로 대체
String result = m.replaceAll("");
out.write(result);
out.newLine();
}
in.close();
out.close();
}
}
파일 검색
/*
* .java 파일에서 주석을 찾아 출력한다.
*/
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
public class CharBufferExample {
public static void main(String[] args) throws Exception {
// 주석을 나타내는 패턴 생성
Pattern p = Pattern.compile("//.*$", Pattern.MULTILINE);
// 소스파일
File f = new File("Replacement.java");
FileInputStream fis = new FileInputStream(f);
FileChannel fc = fis.getChannel();
// 소스 파일로부터 CharBuffer 생성
ByteBuffer bb = fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
Charset cs = Charset.forName("8859_1");
CharsetDecoder cd = cs.newDecoder();
CharBuffer cb = cd.decode(bb);
// 매칭 작업 수행
Matcher m = p.matcher(cb);
while (m.find())
System.out.println("Found comment: "+m.group());
}
}
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
13 | Methods of the Matcher Class | 황제낙엽 | 2010.01.19 | 431 |
12 |
Pattern.matches() , Matcher.matches() , Matcher.find()
![]() | 황제낙엽 | 2010.01.19 | 595 |
11 | 같은 문자열인데도 정규식에서 해당 문자열을 파싱하지 못하는 경우 | 황제낙엽 | 2009.08.08 | 367 |
10 | 문자열 내의 공백을 제거하는 간단한 정규식 | 황제낙엽 | 2009.05.20 | 399 |
9 | 정규표현식을 사용하는 String클래스의 replaceAll() 함수 개량 | 황제낙엽 | 2009.02.09 | 507 |
8 | 입력받은 문자열의 의미가 숫자인지 단순 텍스트인지 판별해야 할 때 | 황제낙엽 | 2009.01.09 | 373 |
7 | 사용팁 | 황제낙엽 | 2008.07.24 | 296 |
» | 정규식 사용예제 [2] | 황제낙엽 | 2008.06.11 | 384 |
5 | 정규식 사용예제 [1] | 황제낙엽 | 2008.06.11 | 436 |
4 | java String.replaceAll (String regex, String replacement) 쓸떄 조심할 것 | 황제낙엽 | 2008.05.22 | 424 |
3 | java String.replaceAll 잘쓰기 | 황제낙엽 | 2008.05.22 | 429 |
2 | Jakarta 프로젝트의 Regexp(정규식) 패키지 사용하기 | 황제낙엽 | 2007.01.22 | 285 |
1 |
PATTERN MATCHING (패턴 매칭)
![]() | 황제낙엽 | 2007.01.17 | 520 |