Java String.matches() 中的正则表达式选项
我想在正则表达式之后添加选项“x”,以在 java 中使用 String.matches() 时忽略空格。但是,我在 http://www.regular-expressions.info/java.html:
Java String 类有几个方法可以让你执行 在该字符串上使用正则表达式进行最少的操作 代码量。缺点是您无法指定诸如 作为“不区分大小写”或“点匹配换行符”。
有没有人有一个使用java的简单方法来解决这个问题,这样我就不必更改我的正则表达式来允许每个可能有空格的地方有零个或多个空格?
I want to add the option 'x' after my regex to ignore white space when using String.matches() in java. However, I see this on http://www.regular-expressions.info/java.html:
The Java String class has several methods that allow you to perform an
operation using a regular expression on that string in a minimal
amount of code. The downside is that you cannot specify options such
as "case insensitive" or "dot matches newline".
Does anyone have an easy way around this using java, so that I don't have to change my regex to allow zero or more white space in every spot there could be white space?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种简单的方法是使用 模式类而不仅仅是使用 matches() 方法。
例如:
An easy way is to use Pattern class instead of just using the matches() method.
For example:
使用 Pattern 类,您可以将选项标志指定为compile 方法的第二个参数,正如 Alvin 所指出的:
但是,如果正则表达式必须是字符串,这对我们没有帮助。例如,当它在配置文件中时。幸运的是,还有另一种方法
嵌入式标志表达式
Using the Pattern class, you can specify option flags as a second parameter to the
compile
method, as pointed out by Alvin:However, this does not help us if the regex must be a string. When it's in a configuration file, for example. Luckily, there is another way
Embedded Flag Expressions
我认为您链接到的网站不准确。查看 JavaDoc 中的 多行标志 ( m),点-所有标志(s) 和 评论标志(x)。
I think the website you linked to is inaccurate. Look at the JavaDoc for the multiline flag (m), the dot-all flag (s), and the comments flag (x).