为什么添加空格会使我的正则表达式出错? [英] Why adding white space makes my regex wrong?

查看:51
本文介绍了为什么添加空格会使我的正则表达式出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(^\s*\d+\)(.*) | ) | (^\s*Q\d+\.\s*(.*))

上述正则表达式与 Q1 不匹配.qeqwewqeqeq qerqer

但是如果我在 |

(^\s*\d+\)(.*) | )|(^\s*Q\d+\.\s*(.*))

它匹配我的字符串.

空白是什么意思?它等于 \s 吗?它会影响我的可读性.

What does white space mean? Is it equal to \s? It affects my readability.

推荐答案

在正则表达式模式中,空格是与空格匹配的有意义的原子.如果您需要使用空格、制表符和换行符来格式化您的模式 - 使用 whitespace 不会被正则表达式引擎考虑 - 您可以使用 (?x) 修饰符,或 Pattern.COMMENTS 标志.

Inside a regex pattern, spaces are meaningful atoms that match spaces. If you need to format your pattern with spaces and tabs and newlines - with whitespace that will not be accounted for by the regex engine - you may use the (?x) modifier, or the Pattern.COMMENTS flag.

然后,要使用 (?x) 选项匹配这种模式中的文字空间,您需要转义空格以匹配文字空间.或者,您可以考虑将任何空格与 \s 匹配:

Then, to match a literal space in such a pattern with (?x) option, you need to escape spaces to match literal spaces. Or, you may consider matching any whitespace with \s:

\s  A whitespace character: [ \t\n\x0B\f\r]

请注意,如果您添加了 (?U) 修饰符,Pattern.UNICODE_CHARACTER_CLASS 标志,\s 将匹配所有 Unicode 空格(如 [\p{Zs}\t\r\n]).

Note that in case you add (?U) modifier, Pattern.UNICODE_CHARACTER_CLASS flag, \s will match all Unicode whitespace (like [\p{Zs}\t\r\n]).

这篇关于为什么添加空格会使我的正则表达式出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆