> Java > java지도 시간 > 본문

자바 패턴 클래스

WBOY
풀어 주다: 2024-08-30 16:00:50
원래의
169명이 탐색했습니다.

Java 패턴 클래스는 정규식의 컴파일된 표현을 생성하는 데 사용되는 java.util 패키지에 제공되는 공개 최종 클래스입니다. 모든 정규식은 이 클래스의 인스턴스로 변환됩니다. 정규식과 일치하는 문자열을 가져오고 문자열이 일치하면 true를 반환하고 그렇지 않으면 false를 반환하는 matcher 메서드로 구성된 Matcher 클래스의 인스턴스를 만드는 데 사용됩니다. 이 클래스의 인스턴스는 변경할 수 없으며 스레드로부터 안전합니다. 즉, 해당 인스턴스는 동시에 작동하는 여러 스레드의 작업에 영향을 미치지 않습니다.

Java 패턴 클래스 메소드

아래는 Java 패턴 클래스 메소드입니다.

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

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

1. 공개 정적 패턴 컴파일(문자열 myregex)

이 방법은 주어진 정규식에서 패턴을 만드는 데 도움이 됩니다.

Parameters The regular expression to be compiled in the form of string.

Example: ( .*) ( \hh) ( .*)

매개변수

문자열 형태로 컴파일할 정규식입니다. 예:
    ( .*) ( \hh) ( .*)
  • 예외:

    메서드에 전달되는 표현식의 구문이 유효하지 않은 경우 PatternSyntaxException이 발생합니다.

    예:

    import java.util.regex.Pattern;
    public class HelloWorld {
    private static final String MYREGEX =  " ( .*) (Learn) ( .*)?";
    public static void main (String[] args) {
    Pattern pattern = Pattern.compile (MYREGEX);
    System.out.println ( "Regular Expression " +pattern.pattern ());
    }
    }
    로그인 후 복사

    코드:

    자바 패턴 클래스

    출력:

    Parameters

     

    a. myregex: The regular expression to be compiled in the form of string.
    b. flag: Flags are the specifications that need to be provided while compiling a regular expression. Example are CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE.

    2. 공개 정적 패턴 컴파일(문자열 myregex, int 플래그) 이 방법은 정규식과 지정된 플래그를 사용하여 Pattern 클래스의 인스턴스를 생성하는 데 도움이 됩니다.

      매개변수
    •  
    아.

    myregex: 문자열 형태로 컴파일할 정규식

    ㄴ.

    플래그: 플래그는 정규식을 컴파일하는 동안 제공해야 하는 사양입니다. 예: CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE.

    예외:
    import java.util.regex.Pattern;
    public class HelloWorld {
    private static final String REGEX =  " ( .*) (Learn) ( .*)?";
    public static void main (String[] args) {
    Pattern pattern = Pattern.compile (REGEX, Pattern.CASE_INSENSITIVE);
    System.out.println ( "Regular Expression " +pattern.pattern ());
    }
    }
    로그인 후 복사

    메서드에 전달되는 표현식의 구문이 유효하지 않은 경우 PatternSyntaxException이 발생합니다.

    비트 값이 전달된 플래그와 일치하는 값과 다른 경우 IllegalArgumentException이 발생합니다.자바 패턴 클래스

    예:

    코드:

    출력:

    import java.util.regex.Pattern;
    public class HelloWorld {
    private static final String REGEX =  " ( .*) (Learn) ( .*)?";
    public static void main (String[] args) {
    Pattern pattern = Pattern.compile (REGEX, Pattern.UNICODE_CHARACTER_CLASS );
    System.out.println ( "Flag for UNICODE_CHARACTER_CLASS " +pattern.flags ());
    Pattern pattern2= Pattern.compile (REGEX, Pattern.UNICODE_CASE );
    System.out.println ( "Flag for UNICODE_CASE " +pattern2.flags ());
    }
    }
    로그인 후 복사

    3. 공개 int 플래그()

    자바 패턴 클래스이 방법은 정규식을 컴파일하여 패턴 클래스의 인스턴스를 생성할 때 설정된 플래그의 정수 값을 가져오는 데 도움이 됩니다.

    예:

    Parameters inputSequence: It is a sequence of character to which we need to match the compiled instance of regex in the form of a pattern object.

    코드:

    출력:

    import java.util.regex.MatchResult;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class HelloWorld {
    private static final String MYREG=  " ( .*) (gu)";
    private static final String SEQ ="Learning regular expression helps a lot in Artificial Intelligence";
    public static void main (String[] args) {
    Pattern pattern = Pattern.compile (MYREG, Pattern.UNICODE_CHARACTER_CLASS );
    Matcher matcherObj = pattern.matcher (SEQ);
    if (matcherObj.find ()) {
    MatchResult res = matcherObj.toMatchResult ();
    System.out.println ( "The offset  : "+res.end ());
    }
    }
    }
    로그인 후 복사

    4. 공개 일치자 일치자(CharSequenceinputSequence)

    이 메서드는 정규식을 주어진 입력 시퀀스와 비교하여 매처 개체의 인스턴스를 만드는 데 사용됩니다. 이 방법을 사용하려면 매개변수 1개를 전달해야 하며 예외가 발생하지 않습니다.자바 패턴 클래스

    매개변수

    inputSequence:

    패턴 개체 형태로 컴파일된 정규식 인스턴스와 일치시키는 데 필요한 문자 시퀀스입니다.

    Parameters inputSequence: It is a sequence of character to which we need to match the compiled instance of regex in the form of a pattern object.
    MyRegex: The regular expression to be compiled in the form of string.
    예: 코드: 출력: 5. 공개 정적 부울 일치(String MyRegex, CharSequenceinputSequence) 이 방법은 주어진 입력 시퀀스를 정규식의 컴파일된 버전과 일치시키는 데 사용됩니다. 매개변수 inputSequence: 패턴 객체 형태로 컴파일된 정규 표현식 인스턴스와 일치시키는 데 필요한 문자 시퀀스입니다. MyRegex: 문자열 형식으로 컴파일할 정규식

    Exception:

    • PatternSyntaxException is thrown when the syntax of the expression is invalid being passed to the method.

    6. public String pattern ()

    This method is used to get the regular expression from which the pattern instance has been compiled. This method requires no parameters to be passed as well as no exception will be thrown.

    An example for this method is shown below with an example of the quote method.

    7. public static String quote (String s)

    This method is used to get the literal string after the pattern is resolved using the method’s flags. This method requires 1 parameter to be passed as well as no exception will be thrown.

    Parameters The string of regular expression that needs to be compiled.

    Example:

    Code:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class HelloWorld {
    private static String myRegx = "location$";
    private static String line= "The location$ office have great capacity of seats for our employess";
    private static String newEx = "Bangalore";
    public static void main (String[] args) {
    Pattern patternObj2 = Pattern.compile (Pattern.quote (myRegx));
    Matcher matcherObj1 = patternObj2.matcher (line);
    line= matcherObj1.replaceAll (newEx);
    System.out.println ( "The Regular expression defined for pattern instance is " +patternObj2.pattern ());
    System.out.println ( "The Input sequence after substitution of Regular Expression  "+ line);
    }
    }
    로그인 후 복사

    Output:

    자바 패턴 클래스

    8. public String[] split (CharaterSequence in)

    This method is used to split the input String argument at every index where regular expression is found. This method requires 1 parameter to be passed as well as no exception will be thrown.

    Parameters  input: The character sequence that is to be split according to the Regular expression specified.

    Example:

    Code:

    import java.util.regex.Pattern;
    public class HelloWorld {
    private static String REGEX = ":";
    private static String INPUT = "BANGLORE:CHENNAI:GUWAHATI:AHMEDABAD";
    public static void main (String[] args) {
    Pattern patternObj2 = Pattern.compile (REGEX);
    String[] result = patternObj2.split (INPUT);
    for (String data:result){
    System.out.println (data+"\n");
    }
    }
    }
    로그인 후 복사

    Output:

    자바 패턴 클래스

    9. public String[] split (CharaterSequencein, intmyThreshHold)

    This method also splits the given input sequence but upto some threshold. This method requires 2 parameters to be passed as well as no exception will be thrown.

    Parameters a. in: The character sequence that is to be split.
    b. myThreshHold: This parameter defines the threshold of splitting operation.

    Example:

    Code:

    import java.util.regex.Pattern;
    public class HelloWorld {
    private static String REGEX = ":";
    private static String INPUT = "BANGLORE:CHENNAI:GUWAHATI:AHMEDABAD";
    public static void main (String[] args) {
    Pattern patternObj2 = Pattern.compile (REGEX);
    String[] result = patternObj2.split (INPUT,3);
    for (String data:result){
    System.out.println (data+"\n");
    }
    }
    }
    로그인 후 복사

    Output:

    자바 패턴 클래스

    10. public String toString ()

    This method is used to get the String representation of the regular expression from which the regular expression has been compiled. This method requires no parameters to be passed as well as no exception will be thrown.

    Example:

    Code:

    import java.util.regex.Pattern;
    public class HelloWorld {
    private static String REGEX = "location$";
    public static void main (String[] args) {
    Pattern patternObj2 =
    Pattern.compile (Pattern.quote (REGEX));
    System.out.println ( "toString representation of pattern instance is " +patternObj2.toString ());
    }
    }
    로그인 후 복사

    Output:

    자바 패턴 클래스

    Conclusion

    Pattern class is used to store the compiled representation of regular expressions from where they are passed to an instance of Matcher class to get the strings that match that regular expression. In this way, one is able to work with regular expressions more efficiently in their application.

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

  • 관련 라벨:
    원천:php
    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!