sitelink1 | |
---|---|
sitelink2 | |
sitelink3 | |
sitelink4 | |
sitelink5 | |
sitelink6 |
This section describes some additional useful methods of the
Matcher
class. For convenience, the methods listed below are grouped according to functionality.이섹션은 Matcher클래스의 일부 추가된 유용한 메소드를 성명한다. 아래에 리스트된 메소드드는 기능에 따라 구룹되어 진다.
Index Methods
Index methods provide useful index values that show precisely where the match was found in the input string:
인덱스 메소드는 유용한 인덱스 값을 제공하는데, 그 값은 입력 문자와 그 매치가 어디에서 발견되었는지 명확하게 보여준다.
public int start()
: Returns the start index of the previous match. 이전 매치의 시작 인덱스 리턴public int start(int group)
: Returns the start index of the subsequence captured by the given group during the previous match operation. 앞의 매치 연산을 하능 동안 주어진 그룹에 의해, 캡처된 하위시퀀스의 시작 인덱스를 리턴한다.public int end()
: Returns the offset after the last character matched. 매친된 마지막 문자 다음의 위치를 리턴한다.public int end(int group)
: Returns the offset after the last character of the subsequence captured by the given group during the previous match operation. 이전 매치연산 동안 주어진 캡처에 의한 하위시퀀스의 마지막 문자 다음의 위치를 리턴한다.Study Methods
Study methods review the input string and return a boolean indicating whether or not the pattern is found.
스터디 메소드는 입력 문자열을 재검토하고, 패턴이 발견되었는지, 아닌지를 나타내는 불린값을 리턴한다.
public boolean lookingAt()
: Attempts to match the input sequence, starting at the beginning of the region, against the pattern. 패턴에 대해 입력시퀀스에 매치를 시도하라.시작점에서 시작하는,public boolean find()
: Attempts to find the next subsequence of the input sequence that matches the pattern. 패턴에 매치하는 입력 시권스의 다음 하위시퀀스를 찾는것을 시도하라.public boolean find(int start)
: Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index. 이 매처를 리셋하고, 패턴에 매치하는 입력 시퀀스의 다음 하위시퀀스를 찾는것을 시도하라. 특별한 위치에서 시작하는,public boolean matches()
: Attempts to match the entire region against the pattern. 패턴에 대해 전체 지역을 매치하라.Replacement Methods
Replacement methods are useful methods for replacing text in an input string.
교환 메소드는 입력 문자열에서 문자 교환을 위한 유용한 메소드다.
public Matcher appendReplacement(StringBuffer sb, String replacement)
: Implements a non-terminal append-and-replace step. 끝이 아닌 추가/교체 단계를 수행하라.public StringBuffer appendTail(StringBuffer sb)
: Implements a terminal append-and-replace step. 끝의 추가/교체 단계를 수행하라public String replaceAll(String replacement)
: Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. 패턴에 매치하는 입력 시퀀스의 모든 하위시퀀스를 주어진 교체문자로 교체하라.public String replaceFirst(String replacement)
: Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string. 패턴에 매치하는 입력문자의 첫번째 하위 문자를 주어준 교체 문자로 교체하라public static String quoteReplacement(String s)
: Returns a literal replacementString
for the specifiedString
. This method produces aString
that will work as a literal replacements
in theappendReplacement
method of theMatcher
class. TheString
produced will match the sequence of characters ins
treated as a literal sequence. Slashes (''
) and dollar signs ('$'
) will be given no special meaning. 명세된 String을 위한 문자상의 교체String를 리턴하라. 이메소드는 Matcher클래스의 appendReplacement 메소드에서 문자상의 교체로써, 작업할 문자열을 만들어 낸다. 만들어진 문자열은 문자상의 시퀀스로써, 다루어진 s의 문자열의 시퀀스와 매치될 것이다. 와 $는 특별한 의미를 갖지 않는다.Using the
start
andend
MethodsHere's an example,
MatcherDemo.java
, that counts the number of times the word "dog" appears in the input string.입력문자열에서 "dog" 단어가 나타나는 횟수를 계산하는 예제가 있다.
You can see that this example uses word boundaries to ensure that the letters·미리보기 | 소스복사·
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class MatcherDemo {
- private static final String REGEX = "bdogb";
- private static final String INPUT = "dog dog dog doggie dogg";
- public static void main(String[] args) {
- Pattern p = Pattern.compile(REGEX);
- Matcher m = p.matcher(INPUT); // get a matcher object
- int count = 0;
- while(m.find()) {
- count++;
- System.out.println("Match number "+count);
- System.out.println("start(): "+m.start());
- System.out.println("end(): "+m.end());
- }
- }
- }
- OUTPUT:
- Match number 1
- start(): 0
- end(): 3
- Match number 2
- start(): 4
- end(): 7
- Match number 3
- start(): 8
- end(): 11
"d" "o" "g"
are not merely a substring in a longer word. It also gives some useful information about where in the input string the match has occurred. Thestart
method returns the start index of the subsequence captured by the given group during the previous match operation, andend
returns the index of the last character matched, plus one. 이 예제가 d,o,g문자들이 더 긴 단어의 하위 문자들이 아니라는것을 입증하기 위해, 단어 경계를 사용하는것을 볼수 있다. start메소드는 이전 매치 연산동안 주언진 그룹에 의해 캨처된 하위 시퀀스의 시작 인덱스를 리턴한다. 그맇고 end 는 매치된 마지막 문자의 인덱스 + 1 값을 리턴한다.Using the
matches
andlookingAt
MethodsThe
matches
andlookingAt
methods both attempt to match an input sequence against a pattern. The difference, however, is thatmatches
requires the entire input sequence to be matched, whilelookingAt
does not. Both methods always start at the beginning of the input string. Here's the full code,MatchesLooking.java
:matche와 lookingAt메소드 모두 패턴에 대해, 입력 시퀀스와 매치하는것을 시도한다. 다른점은 matche는 매치되는 입력 시퀀스 전체를 요구하지만, lookingAt은 그렇지 않다. 두 메소드 모두 입력 문자열의 시작점에서 시작한다.
·미리보기 | 소스복사·
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class MatchesLooking {
- private static final String REGEX = "foo";
- private static final String INPUT = "fooooooooooooooooo";
- private static Pattern pattern;
- private static Matcher matcher;
- public static void main(String[] args) {
- // Initialize
- pattern = Pattern.compile(REGEX);
- matcher = pattern.matcher(INPUT);
- System.out.println("Current REGEX is: "+REGEX);
- System.out.println("Current INPUT is: "+INPUT);
- System.out.println("lookingAt(): "+matcher.lookingAt());
- System.out.println("matches(): "+matcher.matches());
- }
- }
- Current REGEX is: foo
- Current INPUT is: fooooooooooooooooo
- lookingAt(): true
- matches(): false
Using
replaceFirst(String)
andreplaceAll(String)
The
replaceFirst
andreplaceAll
methods replace text that matches a given regular expression. As their names indicate,replaceFirst
replaces the first occurrence, andreplaceAll
replaces all occurences. Here's theReplaceDemo.java
code:replaceFirst 와 replaceAll 메소드는 주어진 정규식과 매치하는 텍스트를 교체한다. 메소드의 이름이 말해주는것 처럼, replaceFirst는 처음 발생한 것과 교체하고, replaceAll는 모든 발생을 교체한다.
In this first version, all occurrences of·미리보기 | 소스복사·
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class ReplaceDemo {
- private static String REGEX = "dog";
- private static String INPUT = "The dog says meow. All dogs say meow.";
- private static String REPLACE = "cat";
- public static void main(String[] args) {
- Pattern p = Pattern.compile(REGEX);
- Matcher m = p.matcher(INPUT); // get a matcher object
- INPUT = m.replaceAll(REPLACE);
- System.out.println(INPUT);
- }
- }
- OUTPUT: The cat says meow. All cats say meow.
dog
are replaced withcat
. But why stop here? Rather than replace a simple literal likedog
, you can replace text that matches any regular expression. The API for this method states that "given the regular expressiona*b
, the inputaabfooaabfooabfoob
, and the replacement string-
, an invocation of this method on a matcher for that expression would yield the string-foo-foo-foo-
."Here's the
ReplaceDemo2.java
code:이 처음 버전에서, dog의 모든 발생은 cat로 대체된다. 그런데 왜 여기는 멈췄는가? dog처럼 간단한 문자열을 교체하는것 보다, 어떤 정규식과 매치하는 텍스트를 교체할수 있다. 이 메소드의 API는 주어진 정규식 a*b, aabfooaabfooabfoob 입력, 그리고 교체문자 -, 그 정규식을 위한 매처에서 이 메소드의 호출은 -foo-foo-foo-를 나타낼것이다. 라고 말한다.
To replace only the first occurrence of the pattern, simply call·미리보기 | 소스복사·
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class ReplaceDemo2 {
- private static String REGEX = "a*b";
- private static String INPUT = "aabfooaabfooabfoob";
- private static String REPLACE = "-";
- public static void main(String[] args) {
- Pattern p = Pattern.compile(REGEX);
- Matcher m = p.matcher(INPUT); // get a matcher object
- INPUT = m.replaceAll(REPLACE);
- System.out.println(INPUT);
- }
- }
- OUTPUT: -foo-foo-foo-
replaceFirst
instead ofreplaceAll
. It accepts the same parameter. 단지 패턴의 처음 발생을 교체하기 위해, replaceAll대신에 replaceFirst를 호출할수 있다. 같은 파라미터를 허용한다.Using
appendReplacement(StringBuffer,String)
andappendTail(StringBuffer)
The
Matcher
class also providesappendReplacement
andappendTail
methods for text replacement. The following example,RegexDemo.java
, uses these two methods to achieve the same effect asreplaceAll
.텍스트 교체를 위해, Matcher클래스는 appendReplacement와 appendTail메소드를 제공한다. 다음예제는, replaceAll과 같은 효과를 내기 위해 사용한다.
·미리보기 | 소스복사·
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class RegexDemo {
- private static String REGEX = "a*b";
- private static String INPUT = "aabfooaabfooabfoob";
- private static String REPLACE = "-";
- public static void main(String[] args) {
- Pattern p = Pattern.compile(REGEX);
- Matcher m = p.matcher(INPUT); // get a matcher object
- StringBuffer sb = new StringBuffer();
- while(m.find()){
- m.appendReplacement(sb,REPLACE);
- }
- m.appendTail(sb);
- System.out.println(sb.toString());
- }
- }
- OUTPUT: -foo-foo-foo-
Matcher Method Equivalents in
For convenience, thejava.lang.String
String
class mimics a couple ofMatcher
methods as well:
public String replaceFirst(String regex, String replacement)
: Replaces the first substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the formstr.replaceFirst(regex, repl)
yields exactly the same result as the expressionPattern.compile(regex).matcher(str).replaceFirst(repl)
주어진 정규식에 매치하는 이 문자열의 첫번째 하위문자열을 주어진 replacement로 교체하라. Pattern.compile(regex).matcher(str).repaceFirst(repl)과 같은 표현이다.
public String replaceAll(String regex, String replacement)
: Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the formstr.replaceAll(regex, repl)
yields exactly the same result as the expressionPattern.compile(regex).matcher(str).replaceAll(repl) 주어진 정규식에 매치하는 이 문자열의 각 하위 문자열을 주어진 replacement로 교체하라. Pattern.compile(regex).matcher(str).replaceAll(repl)과 같은 결과를 낸다.
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
» | 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 |
6 | 정규식 사용예제 [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 |