> Java > java지도 시간 > 본문

Java의 정규식

WBOY
풀어 주다: 2024-08-30 15:33:26
원래의
269명이 탐색했습니다.

Java에서, Regex 또는 정규 표현식은 문자열을 검색, 조작 및 편집하기 위한 패턴을 정의하는 데 도움이 되는 응용 프로그램 인터페이스입니다. Java 정규식은 비밀번호 및 이메일 검증에 널리 사용됩니다. 이러한 표현식은 java.util.regex 패키지에서 제공되며 1개의 인터페이스와 3개의 클래스로 구성됩니다.

세 가지 수업은 다음과 같습니다.

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

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

  • 패턴: 패턴 정의에 도움이 됩니다.
  • Matcher: 패턴을 사용하면 일치 작업을 수행하는 데 도움이 됩니다.
  • PatternSyntaxException: 구문 오류를 나타내는 데 도움이 됩니다.

Java Regex에는 정규식의 일치 작업 결과를 결정하는 데 도움이 되는 MatchResultInterface라는 인터페이스가 하나 있습니다.

Java 정규식 구문

프로그램의 도움을 받아 Java에서 정규식을 작성하는 방법을 살펴보겠습니다.

코드:

//Java program to demonstrate regular expressions
import java.util.regex.*;
public class RegExamples {
public static void main(String args[]){
String A = " Happiness is " + " within yourself";
String B = ".*within.*";
// checks whether the string A contains the word 'within' and stores the result in matchcheck
boolean matchcheck = Pattern.matches(B, A);
//prints the result
System.out.println("Is there any string 'within' in the text ? \n " + matchcheck);
}   }
로그인 후 복사

출력:

Java의 정규식

정규 표현식에서 일반적으로 사용되는 메소드

정규식에는 일반적으로 사용되는 메서드가 3가지 있습니다.

1. 색인 방법

인덱스 메소드는 입력으로 제공된 문자열에서 일치 항목이 발견된 위치를 정확하게 표시하는 데 도움이 되는 인덱스 값을 제공합니다.

Method Description
start() The previous match’s start index is returned.
start(int group) Given the group’s previous match operation, the subsequence is captured and returned.
end() The offset after matching the last character is returned.
End(int group) Given the group’s previous match operation, subsequence is captured and offset after matching its last character returned.
방법

설명

시작() 이전 경기의 시작 인덱스가 반환됩니다. 시작(int 그룹) 그룹의 이전 일치 작업을 고려하여 하위 시퀀스가 ​​캡처되어 반환됩니다. 끝() 마지막 문자를 일치시킨 후의 오프셋이 반환됩니다. 종료(int 그룹) 그룹의 이전 일치 작업을 고려하여 하위 시퀀스가 ​​캡처되고 반환된 마지막 문자와 일치한 후 오프셋됩니다. 2. 학습방법
Method Description
lookingAt() Match the sequence given as input against the pattern from the beginning of the region.
find() Finds the next subsequence of the sequence given as input against the pattern from the beginning of the region.
find(int start) Resets the matcher and then finds the next subsequence of the sequence given as input against the specified index pattern.
matches() Matches content against the pattern.

학습 방법은 입력으로 주어진 문자열을 확인하고 패턴이 발견되었는지 여부를 나타내는 부울 값을 반환합니다.

방법

Method Description
appendReplacement(StringBuffer s, String replacement) A non-terminal append and replacement step will be implemented.
appendTail(StringBuffer s) A terminal append and replacement step will be implemented.
replaceAll(String replacement) Replace all subsequence of the sequence given as input that matches against the pattern with a replacement string.
quoteReplacement(String s) A literal replacement string will be returned for the mentioned string.
replaceFirst(String replacement) Replace the first subsequence of the sequence given as input that matches the pattern with a replacement string.
설명 LookingAt() 입력으로 제공된 시퀀스를 영역 시작 부분의 패턴과 일치시킵니다. 찾기() 영역 시작 부분부터 패턴에 대해 입력으로 제공된 시퀀스의 다음 하위 시퀀스를 찾습니다. 찾기(int start) 매처를 재설정한 후 지정된 인덱스 패턴에 대해 입력으로 제공된 시퀀스의 다음 하위 시퀀스를 찾습니다. 일치() 콘텐츠를 패턴과 일치시킵니다. 3. 교체 방법 문자열의 텍스트를 바꾸는 데 사용되는 방법 방법 설명 appendReplacement(StringBuffer s, 문자열 교체) 비터미널 추가 및 교체 단계가 구현됩니다. appendTail(StringBuffer s) 단말기 추가 및 교체 단계가 구현됩니다. replaceAll(문자열 교체) 패턴과 일치하는 입력으로 제공된 시퀀스의 모든 하위 시퀀스를 대체 문자열로 바꿉니다. quoteReplacement(문자열 s) 언급된 문자열에 대해 리터럴 대체 문자열이 반환됩니다. replaceFirst(문자열 교체) 패턴과 일치하는 입력으로 제공된 시퀀스의 첫 번째 하위 시퀀스를 대체 문자열로 바꿉니다.

How to Define Regular Expression in Java?

There are several ways in which a regular expression can be defined.

1. Literals

Suppose a string “hai” has to be searched in the text “hai”.

It can be done using syntax.

Pattern.matches("hai", "hai")
로그인 후 복사

2. Character Classes

It matches every single character in the text given as input against multiple permitted characters in the character class.

The following are the various class constructs.

Character Class Explanation
[pqr] Matches the text if it contains either p, q or r, and it should be only once.
[^pqr] ^ denotes the negation, and due to that, here, single character except for p, q, or r are taken.
[a-zA-Z] a to z and A to Z are considered.
[a-d[p-s]] a to d, or p to s.
[a-dm-p] Union of both ranges.
[a-z&&[pqr]] a to z and (p, q or r).
[a-z&&[^pq]] a to z and also, p, q are not considered.
[ad-z] Performs the subtraction.
[a-z&&[^m-p]] a to z and not m to p.

3. Metacharacters

Metacharacters act like shortcodes in the regular expression.

The following are some of the metacharacters commonly used.

Regular Expression Explanation
\d Any digit from 0 to 9. It can be written as [0-9] as well.
\D Any non-digit from 0 to 9. It can be written as [^0-9] as well.
\s Whitespace character or [\t\n\x0B\f\r].
\S Non whitespace character or [^\s].
\w Word character or [a-zA-Z_0-9].
\W Non-word character or [^\w].
\b Word boundary.
\B Non-word boundary.

4. Quantifiers

Quantifiers mention the count of occurrence of each character to match against the string.

Regular Expression Explanation
a? It occurs once or not at all.
A* A occurs 0 or more times.
A+ A occurs 1 or more times.
A{n} A occurs exactly n times.
A{n,} A occurs n or more than that.
A{n,m} A occurs at least n times, but it should not be more than m times.

How to Create Regular Expression in Java?

Now, let us see a java program with the above-mentioned regular expressions.

Code:

//Java program to demonstrate regular expressions
import java.util.regex.*;
public class RegExamples {
public static void main(String args[]){
String str="hai";
// Returns true if string 1 matches string 2
System.out.println("Returns true if 'hai' matches 'Hai' :"+
Pattern.matches(str, "Hai")); //False
//Returns true if Hai or hai matches parameter 2
System.out.println("Returns true if 'Hai' or 'hai' matches 'Hai' : "+
Pattern.matches("[Hh]ai", "Hai")); //True
// Returns true if the string matches exactly "ann" or "Ann" or "jak" or "Jak"
System.out.println("Returns true if the string matches exactly 'ann' or 'Ann' or 'jak' or 'Jak' with 'Ann' : "+
Pattern.matches("[aA]nn|[jJ]ak", "Ann"));//True
//returns true if the string contains "with" at any place in the string
System.out.println("returns true if the string contains 'with' in the string 'within' : " +
Pattern.matches(".*with.*", "within"));//True
// returns true if the '9448anna' does not have number in the beginning
System.out.println( "returns true if the '9448anna' does not have number in the beginning : "+
Pattern.matches("^[^\\d].*", "9448anna")); //False
System.out.println("returns true if the '9448anna' does not have number in the beginning : " +
Pattern.matches("^[^\\d].*", "anna9448")); //True
}
}
로그인 후 복사

Output:

Java의 정규식

Conclusion – Regular Expressions in Java

Java Regular Expressions are widely used for real-time applications such as password and email verification. These expressions are APIs that define patterns and offer searching, editing, and several other operations in the string.

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

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