[英]Regex options in Java String.matches()
我想在我的正則表達式后面添加選項'x',以便在java中使用String.matches()時忽略空格。 但是,我在http://www.regular-expressions.info/java.html上看到了這一點:
Java String類有幾種方法,允許您使用最少量代碼在該字符串上使用正則表達式執行操作。 缺點是你不能指定諸如“不區分大小寫”或“點匹配換行符”之類的選項。
有沒有人有一個簡單的方法使用java,所以我不必更改我的正則表達式允許零或更多的空白在每個點可能有空格?
一種簡單的方法是使用Pattern類而不是僅使用matches()方法。
例如:
Pattern ptn = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher mtcher = ptn.matcher(myStr)
....
我認為您鏈接的網站不准確。 查看JavaDoc以獲取多行標志(m) , dot-all標志和comments標志(x) 。
使用Pattern類,您可以將選項標志指定為compile
方法的第二個參數,如Alvin所指出的:
Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE).matcher("Hello").matches() // true
但是,如果正則表達式必須是字符串,這對我們沒有幫助。 例如,當它在配置文件中時。 幸運的是,還有另一種方式
也可以使用嵌入的標志表達式啟用各種標志。 嵌入式標志表達式是編譯的雙參數版本的替代,並且在正則表達式本身中指定。
Enter your regex: (?i)foo
Enter input string to search: FOOfooFoOfoO
I found the text "FOO" starting at index 0 and ending at index 3.
I found the text "foo" starting at index 3 and ending at index 6.
I found the text "FoO" starting at index 6 and ending at index 9.
I found the text "foO" starting at index 9 and ending at index 12.
與Pattern的可公開訪問字段對應的嵌入式標志表達式如下表所示:
Constant Equivalent Embedded Flag Expression
Pattern.CANON_EQ None
Pattern.CASE_INSENSITIVE (?i)
Pattern.COMMENTS (?x)
Pattern.MULTILINE (?m)
Pattern.DOTALL (?s)
Pattern.LITERAL None
Pattern.UNICODE_CASE (?u)
Pattern.UNIX_LINES (?d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.