- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- Java中的Pattern.compile函數有什么用
本篇內容主要講解“Java中的Pattern.compile函數有什么用”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強。下面就讓小編來(lái)帶大家學(xué)習“Java中的Pattern.compile函數有什么用”吧!
除了Pattern Pattern.compile(String regex),
Pattern類(lèi)的compile()方法還有另一個(gè)版本:
Pattern Pattern.complie(String regex,int flag),它接受一個(gè)標記參數flag,以調整匹配的行為。
flag來(lái)自以下Pattern類(lèi)中的常量:
在這些標記中 Pattern.CASE_INSENSITIVE(?i) ,Pattern.MULTLINE(?m),==Pattern.COMMENTS(?x)==中特別有用。
使用示例如下:
我們可以通過(guò)“或”( | )操作組合多個(gè)標記的功能
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReFlags { public static void main(String[] args) { Pattern p=Pattern.compile("^java",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE); /* * 使用Pattern.CASE_INSENSITIVE(大小寫(xiě)不敏感的匹配)和Pattern.MULTILINE(多行模式)標記,忽略大小寫(xiě)地匹配所有以java開(kāi)頭的行 */ Matcher m=p.matcher("java has regex\nJava has regex\n" + "JAVA has pretty good regular expression\n" + "Regular expressions are in JavA"); while (m.find()) { System.out.println(m.group());//輸出已匹配的部分 } } }
輸出結果:
java Java JAVA
使用Pattern.COMMENTS(?x)的例子:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReFlags_Comments { public static void main(String[] args) { /* * 不使用Pattern.COMMENTS(不啟動(dòng)注釋) */ String s="123"; Pattern p1=Pattern.compile(" (\\d+)+#test comments"); Matcher m1=p1.matcher(s); System.out.println(m1.matches());//false /* * 正則表達式中使用啟動(dòng)注釋的標記 */ Pattern p2=Pattern.compile("(?x) (\\d+)+#test comments"); Matcher m2=p2.matcher(s); System.out.println(m2.matches());//true /* * 參數中使用Pattern.COMMENTS以啟動(dòng)注釋 */ Pattern p3=Pattern.compile(" (\\d+)+#test comments",Pattern.COMMENTS); Matcher m3=p3.matcher(s); System.out.println(m3.matches());//true } }
運行結果:
false true true
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站