首頁 > Java > java教程 > Java 中的正規表示式

Java 中的正規表示式

WBOY
發布: 2024-08-30 15:33:26
原創
353 人瀏覽過

在 Java 中,Regex 或正規表示式是一種應用程式介面,可協助定義搜尋、操作和編輯字串的模式。 Java 正規表示式廣泛用於密碼和電子郵件的驗證。這些表達式由 java.util.regex 套件提供,由 1 個介面和 3 個類別組成。

這三個類別是:

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

  • 模式:幫助定義模式。
  • 匹配器:使用模式有助於執行匹配操作。
  • 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開始) 重設匹配器,然後根據指定的索引模式尋找作為輸入給出的序列的下一個子序列。 匹配() 將內容與模式配對。 表> 3.更換方法 用來替換字串中文字的方法。 方法 描述 appendReplacement(StringBuffer s, 字串替換) 將實施非終止附加和替換步驟。 appendTail(StringBuffer s) 將實施終端追加和替換步驟。 replaceAll(字串替換) 以替換字串替換作為輸入給出的與模式匹配的序列的所有子序列。 quoteReplacement(String 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板