>  기사  >  Java  >  자바 일치

자바 일치

王林
王林원래의
2024-08-30 16:00:27689검색

Java Matcher 클래스는 Java Regex 패키지의 클래스 중 하나입니다. Java Matcher 클래스 및 패턴은 정규식에 대한 클래스 및 인터페이스를 생성하는 기능을 제공하는 Regex 패키지의 일부입니다. 정규식의 작업과 문자 시퀀스를 찾은 다음 정규식의 다른 문자 시퀀스와 비교하여 일치 항목을 찾는 데 도움이 됩니다. 일치 항목이 적중되면 MatchResult 인터페이스라는 인터페이스가 생성됩니다. 정규식 엔진은 정의된 문자 시퀀스 일치 시나리오를 수행하고 인터페이스를 생성하는 데 사용됩니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java Matcher 클래스 메서드

수업 방법은 다음과 같습니다.

  • 공개 부울 일치()
  • 공개 부울 find()
  • 공개 부울 찾기(int 시작)
  • 공개 문자열 그룹()
  • public int start() 및 int start(int 그룹)
  • public int end() 및 int end(int 그룹)
  • 공용 int groupCount()
  • 공개 부울 lookingAt()
  • 공개 일치자 추가 교체()
  • 공용 StringBufferappendTail()
  • 공개 문자열 바꾸기All()
  • 공용 문자열 바꾸기First()
  • 공개 정적 문자열 quoteReplacement()

1. 공개 부울 일치()

boolean match()는 정규 표현식이 패턴과 일치하는지 테스트하는 데 사용되는 Java Matcher 클래스 내의 메서드입니다.

:

이 프로그램은 Java Matcher 클래스의 공개 부울 match() 메서드를 패턴으로 보여줍니다.

코드:

import java.util.regex.*;
public class BooleanRegMatches{
public static void main(String args[])
{
System.out.println(Pattern.matches("[banana]", "qda"));
System.out.println(Pattern.matches("[mango]", "mn"));
System.out.println(Pattern.matches("[orange]", "e"));
}
}

출력:

자바 일치

2. 공개 부울 찾기()

이 메소드는 패턴과 일치할 수 있고 인터페이스를 생성하는 데 사용할 수 있는 다음 표현식을 찾아서 일치시키는 데 사용되는 matcher 클래스의 일부입니다.

예:

이 프로그램은 일치시킬 정규식을 찾아서 패턴과 비교하여 인터페이스를 만드는 데 사용됩니다.

코드:

import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;
public class Regx_Pattrn_1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (true) {
System.out.println("consider a regulr exprssn for traversing:");
Pattern pattern_k = Pattern.compile(sc.nextLine());
System.out.println("Next Text to Execute:");
Matcher matcher_g = pattern_k.matcher(sc.nextLine());
boolean found = false;
while (matcher_g.find()) {
System.out.println(" Text needs to be searched  "+matcher_g.group()+" from starting index "+
matcher_g.start()+" and from ending index "+matcher_g.end());
found = true;
}
if(!found){
System.out.println("No match is found after comparison");
}
}
}
}

출력:

자바 일치

3. 공개 부울 찾기(int 시작)

이 방법은 처음부터 시작하는 정규식과 끝 인덱스가 일치하는 방법을 찾는 데 사용됩니다.

예:

이 프로그램은 정규식의 시작 및 끝 인덱스를 제공하는 부울 find(int start) 메서드를 보여줍니다.

코드:

import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;
public class Java_Pattrn_2 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (true) {
System.out.println("Form one reg_expression pattern:");
Pattern pattern_j = Pattern.compile(sc.nextLine());
System.out.println("Neeed to match some part of the string for execution:");
Matcher matcher_o = pattern_j.matcher(sc.nextLine());
boolean found1 = false;
while (matcher_o.find()) {
System.out.println("got the pattern initiated where "+matcher_o.group()+" index_is_starting "+
matcher_o.start()+" index_is_ending "+matcher_o.end());
found1 = true;
}
if(!found1){
System.out.println("Some kind of mismatch is prevailing");
}
}
}
}

출력:

자바 일치

4. 공개 문자열 그룹()

이 메소드는 이후에 정규식과 일치하는 문자열을 반환하는 Java Matcher 클래스의 일부입니다.

예:

이 프로그램은 일치 문자열에 도달한 후 정규 표현식의 후속 하위 문자열을 생성하려고 시도하는 Java Matcher 클래스의 String 그룹() 메소드를 보여줍니다.

코드:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regx_Pttrn_3 {
public static void main(String[] args) {
String reg_exprn_txt ="I am trying to learn something new, and trying to learning something from there," +
" and will one day become a skilled person. ";
String pattern_one_str = "(trying)";
Pattern pattrn_7 = Pattern.compile(pattern_one_str);
Matcher matchr_0 = pattrn_7.matcher(reg_exprn_txt);
while(matchr_0.find()) {
System.out.println(" Matched_Value: " + matchr_0.group(1));
}
}
}

출력:

자바 일치

5. public int start() 및 int start(int 그룹)

Java Matcher 클래스의 일부인 int start() 및 int start(int group) 메서드는 그룹화된 문자열의 시작 인덱스가 있는 문자열 하위 문자열의 후속 값을 가져오는 데 사용됩니다.

:

이 프로그램은 문자열 그룹화 후 정규식의 시작 인덱스와 일치하는 후속 일치 문자열을 찾는 방법을 보여줍니다.

코드:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regx_Pttrn4 {
public static void main(String[] args) {
String reg_txt_exprssion    =
"This text needs to be done " +
"with some careful attention 'done'.";
String string_grouping = "done";
Pattern pattern_l = Pattern.compile(string_grouping);
Matcher matcher_l = pattern_l.matcher(reg_txt_exprssion);
int count = 0;
while(matcher_l.find()) {
count++;
System.out.println("Matching_context: " + count + " : "
+ matcher_l.start());
}
}
}

출력:

자바 일치

6. public int end() 및 int end(그룹 내)

이 메서드는 일치하는 후속 문자열 패턴의 하위 문자열 끝 인덱스를 반환하는 데 사용됩니다.

예:

이 프로그램은 Java Matcher 클래스의 int end(그룹 내) 메소드를 시연하는 데 사용됩니다.

코드:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regx_Pattrn5 {
public static void main(String[] args) {
String Expression    =
"Some special substring characters and escape characters need to be searched for. " +
"that to get the number of hits on the given expression of the text 'to'.";
String string_Pattrn = "to";
Pattern pattern_f = Pattern.compile(string_Pattrn);
Matcher matcher_f = pattern_f.matcher(Expression);
int count = 0;
while(matcher_f.find()) {
count++;
System.out.println("match_found: " + count + " : "
+ matcher_f.end());
}
}
}

출력:

자바 일치

7. 공개 정수 그룹 개수

이 메소드는 reg 표현식과 일치하는 하위 문자열을 비교한 후 정규 표현식 세트로 존재하는 그룹 수를 반환하는 데 사용됩니다.

예:

이 프로그램은 Java Matcher 클래스의 int 그룹 카운트 방법을 보여줍니다.

코드:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regx_Pattrn_6 {
public static void main(String[] args) {
String run_Exp  = " I am fond of eating delicious and yummy food everythime, and my mom is also fond of cooking that," +
" and dad also wants to taste the yummy food.";
String patternString1 = "(fond) (.+?) ";
Pattern pattern_s = Pattern.compile(patternString1);
Matcher matcher_s = pattern_s.matcher(run_Exp);
while(matcher_s.find()) {
System.out.println("matching_found_present: " +  "count:"+ matcher_s.group(1) +
" "       + matcher_s.group(2));
}
}
}

출력:

자바 일치

8. public boolean lookingat()

As part of the matcher class, this method only tries to match the beginning of the text, not the entire text, which means, unlike the matcher class, which considers the entire regular expression for matching and result.

Example:

This program demonstrates the boolean lookingat() method of the Java Matcher class.

Code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regx_Pattrn_7 {
public static void main(String[] args) {
String String_expr = "An expression to search and match the string pattern " + "make a search for the pattern.";
String String_ptrn = "pattern";
Pattern pattern_k = Pattern.compile(String_ptrn, Pattern.CASE_INSENSITIVE);
Matcher matcher_k = pattern_k.matcher(String_expr);
System.out.println("currently_looking_At = " + matcher_k.lookingAt());
System.out.println("currently_matches   = " + matcher_k.matches());
}
}

Output:

자바 일치

9. public Matcher appendReplacement()

This method is used to replace the set of text in the regular expression and then append that input string into the string buffer. It keeps a check on the string buffer what is being copied and what is needed to be replaced.

Example:

This program demonstrates the Matcher appendReplacement() method of Java Matcher.

Code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regex_Pttrn_8 {
public static void main(String[] args) {
String sm_txt  =  "I love to read books of harry potter, and i also love to read books of JK Rowling" +   " and My favourite writer writes all fiction books.";
String String_ptrn1 = "((books) (.+?)) ";
Pattern pattern_o = Pattern.compile(String_ptrn1);
Matcher matcher_o = pattern_o.matcher(sm_txt);
StringBuffer stringBuffer = new StringBuffer();
while(matcher_o.find()){
matcher_o.appendReplacement(stringBuffer, " fiction books ");
System.out.println(stringBuffer.toString());
}
}
}

Output:

자바 일치

10. public StringBuffer appendTail()

This method also behaves in a similar fashion with a difference that if the last match is found from the input text and is not yet copied to the string buffer, then it is needed to check for the required text and can append at the end of the expression and then can be copied into the buffer.

Example:

This program demonstrates the StringBuffer append Tail() method of Java Matcher.

Code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Regex_Pttrn_8 {
public static void main(String[] args) {
String sm_txt  =  "I love to read books of harry potter, and i also love to read books of JK Rowling" +  " and My favourite writer writes all fiction books.";
String String_ptrn1 = "((books) (.+?)) ";
Pattern pattern_p = Pattern.compile(String_ptrn1);
Matcher matcher_p = pattern_p.matcher(sm_txt);
StringBuffer stringBuffer = new StringBuffer();
while(matcher_p.find()){
matcher_p.appendReplacement(stringBuffer, " fiction books ");
System.out.println(stringBuffer.toString());
}
matcher_p.appendTail(stringBuffer);
System.out.println(stringBuffer.toString());
}
}

Output:

자바 일치

11. public String replaceAll()

As its name suggests, the String replaceAll () method can replace all the found matches and matched groups with the regular expression.

Example:

This program demonstrates the String replaceAll() method of Java Matcher.

Code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Java_Reg_Replace {
public static void main(String[] args) {
String one_ptrn    ="I want to have a cup of tea, and I also want to have a cup of coffe at the same time," +
" and also want to have toffee.";
String ptrn_ex_strng = "((cofee) (.+?)) ";
Pattern pattern1 = Pattern.compile(ptrn_ex_strng);
Matcher matcherb = pattern1.matcher(one_ptrn);
String replaceAll = matcherb.replaceAll("tea or coffee ");
System.out.println("replaceAll   = " + replaceAll);
}
}

Output:

자바 일치

12. public String replaceFirst()

This method is used for replacing the string text from the beginning of the regular expression as soon as the first match gets hit.

Example:

This program demonstrates the replaceFirst() method of Java Matcher.

Code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Java_Reg_Replace {
public static void main(String[] args) {
String one_ptrn    ="I want to have a cup of tea, and I also want to have a cup of coffe at the same time," + " and also want to have toffee.";
String ptrn_ex_strng = "((cofee) (.+?)) ";
Pattern pattern1 = Pattern.compile(ptrn_ex_strng);
Matcher matcherb = pattern1.matcher(one_ptrn);
String replaceAll = matcherb.replaceAll("tea or coffee ");
System.out.println("replaceAll   = " + replaceAll);
String replaceFirst = matcherb.replaceFirst("tea or coffee ");
System.out.println("replaceFirst = " + replaceFirst);
}
}

Output:

자바 일치

13. public static String quoteReplacement()

It is a mediator method of all the replace methods and is used when the string and the characters in the string need to be replaced with the parameters passed as a replaced parameter.

Example:

This program demonstrates the String quoteReplacement() method of Java Matcher.

Code:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class reg_quote_replcment {
public static void main(String[] args) {
String reg_exprsn = "Welcome Everyone";
Pattern pattern_a = Pattern.compile(reg_exprsn);
String stringNeedsToMatch  = "Welcome evryone to the laerning portal of educba";
Matcher matcher_b = pattern_a.matcher(stringNeedsToMatch);
String stringToBeReplaced = "Welcome";
System.out.println(matcher_b .quoteReplacement(stringToBeReplaced));
}
}

Output:

자바 일치

Conclusion

Java Matcher class is a class which is part of Java regex package and mainly deals with the regular expressions and its functioning with the other regular function at the index level, replacement methods and quotereplacement method. It has simplified the overall manipulation of the strings and characters of the string for regular expressions.

위 내용은 자바 일치의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Java의 중첩 클래스다음 기사:Java의 중첩 클래스