[英]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.