Dalam Java, Regex atau Regular Expression ialah Antara Muka Program Aplikasi yang membantu menentukan corak untuk mencari, memanipulasi dan mengedit rentetan. Ungkapan biasa Java digunakan secara meluas dalam pengesahan kata laluan dan e-mel. Ungkapan ini disediakan oleh pakej java.util.regex dan terdiri daripada 1 antara muka dan 3 kelas.
Tiga kelas tersebut ialah:
Mulakan Kursus Pembangunan Perisian Percuma Anda
Pembangunan web, bahasa pengaturcaraan, ujian perisian & lain-lain
Java Regex mempunyai satu antara muka yang dikenali sebagai MatchResultInterface yang membantu dalam menentukan hasil operasi padanan ungkapan biasa.
Mari kita lihat cara menulis ungkapan biasa dalam Java dengan bantuan program.
Kod:
//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); } }
Output:
Terdapat 3 kaedah yang biasa digunakan dalam ungkapan biasa.
Kaedah indeks menawarkan nilai indeks yang membantu dalam menunjukkan dengan tepat di mana padanan ditemui dalam rentetan yang diberikan sebagai input.
|
Penerangan | ||||||||||
start() | Indeks permulaan perlawanan sebelumnya dikembalikan. | ||||||||||
start(int group) | Memandangkan operasi perlawanan kumpulan sebelumnya, urutan itu ditangkap dan dikembalikan. | ||||||||||
end() | Offset selepas sepadan dengan aksara terakhir dikembalikan. | ||||||||||
Tamat(int group) | Memandangkan operasi padanan kumpulan sebelumnya, urutan ditangkap dan diimbangi selepas memadankan aksara terakhir yang dikembalikan. |
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. |
Kaedah |
|
||||||||||||
lookingAt() | Padankan jujukan yang diberikan sebagai input terhadap corak dari permulaan rantau. | ||||||||||||
cari() | Mencari jujukan seterusnya bagi jujukan yang diberikan sebagai input terhadap corak dari permulaan rantau. | ||||||||||||
cari(int mula) | Menetapkan semula padanan dan kemudian mencari jujukan seterusnya bagi jujukan yang diberikan sebagai input terhadap corak indeks yang ditentukan. | ||||||||||||
padan() | Padankan kandungan dengan corak. |
Kaedah | Penerangan |
appendReplacement(StringBuffer s, Penggantian rentetan) | Langkah tambahan dan penggantian bukan terminal akan dilaksanakan. |
appendTail(StringBuffer s) | Lampiran terminal dan langkah penggantian akan dilaksanakan. |
replaceAll(Penggantian rentetan) | Ganti semua urutan urutan yang diberikan sebagai input yang sepadan dengan corak dengan rentetan gantian. |
quoteReplacement(String s) | Rentetan penggantian literal akan dikembalikan untuk rentetan yang disebutkan. |
replaceFirst(Penggantian rentetan) | Ganti urutan pertama jujukan yang diberikan sebagai input yang sepadan dengan corak dengan rentetan gantian. |
There are several ways in which a regular expression can be defined.
Suppose a string “hai” has to be searched in the text “hai”.
It can be done using syntax.
Pattern.matches("hai", "hai")
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. |
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. |
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. |
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 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.
Atas ialah kandungan terperinci Ungkapan Biasa di Jawa. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!