Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java String.matches()中的正则表达式选项_Java_Regex_Whitespace - Fatal编程技术网

Java String.matches()中的正则表达式选项

Java String.matches()中的正则表达式选项,java,regex,whitespace,Java,Regex,Whitespace,在java中使用String.matches()时,我想在正则表达式后面添加选项“x”,以忽略空白。然而,我看到了这一点: Java字符串类有几个方法,允许您执行 在极小值中对该字符串使用正则表达式的操作 代码量。缺点是不能指定这样的选项 如“不区分大小写”或“点匹配换行符” 有没有人能用java轻松解决这个问题,这样我就不必更改我的正则表达式,在每个可能存在空白的地方都允许零或更多的空白?我认为你链接的网站不准确。查看JavaDoc中的、和。一个简单的方法是使用类,而不仅仅是使用matches

在java中使用String.matches()时,我想在正则表达式后面添加选项“x”,以忽略空白。然而,我看到了这一点:

Java字符串类有几个方法,允许您执行 在极小值中对该字符串使用正则表达式的操作 代码量。缺点是不能指定这样的选项 如“不区分大小写”或“点匹配换行符”


有没有人能用java轻松解决这个问题,这样我就不必更改我的正则表达式,在每个可能存在空白的地方都允许零或更多的空白?

我认为你链接的网站不准确。查看JavaDoc中的、和。

一个简单的方法是使用类,而不仅仅是使用matches()方法

例如:

Pattern ptn = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher mtcher = ptn.matcher(myStr)
....

使用Pattern类,您可以指定选项标志作为
compile
方法的第二个参数,正如Alvin所指出的:

Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE).matcher("Hello").matches() // true
但是,如果正则表达式必须是字符串,这对我们没有帮助。例如,当它位于配置文件中时。幸运的是,还有另一种方法

还可以使用嵌入的标志表达式启用各种标志。嵌入式标志表达式是compile的两参数版本的替代,并在正则表达式本身中指定

下表显示了与模式的公共可访问字段相对应的嵌入式标志表达式:


我认为这个网站是正确的,因为你不能通过String类设置这些标志。也许技术上是正确的,但是误导性的,因为它没有告诉读者,像我指出的那样,Pattern类中有这样的功能。因此,我认为不准确是一个公平的描述。很高兴知道这也是可能的。我想,这会使实现更容易,而且在Java代码之外唯一可配置的东西是正则表达式的情况下,它很有用。谢谢@stijn de witt@2011年,我认为这应该是公认的答案。问题是要求一个“简单的方法”,在许多情况下,在正则表达式中更改几个字符是最简单的选择。
模式
方法使其更为明确,但在某些情况下可能无法实现。
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.
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)