我可以定义自定义字符类的简写吗? [英] Can I define custom character class shorthands?

查看:44
本文介绍了我可以定义自定义字符类的简写吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java提供了一些有用的字符类,例如 \ d \ w .我可以定义自己的角色类吗?例如,能够为 [A-Za-z _] 之类的字符类定义简写会很有用.

Java provides some useful character classes like \d and \w. Can I define my own character classes? For example, it would be useful to be able to define shorthands for character classes like [A-Za-z_].

推荐答案

我可以定义自己的角色类吗?

Can I define my own character classes?

不,你不能.

就我个人而言,当我有一个(略微)复杂的正则表达式时,我将正则表达式分解成较小的子正则表达式,然后将它们与 String.format(...)一起粘在一起这个:

Personally, when I have a (slightly) complicated regex, I break the regex up in smaller sub-regexes and then "glue" them together with a String.format(...) like this:

public static boolean isValidIP4(String address) {
    String block_0_255 = "(0|[1-9]\\d|2[0-4]\\d|25[0-5])";
    String regex = String.format(
            "%s(\\.%s){3}", 
            block_0_255, block_0_255
    );
    return address.matches(regex);
}

比单个模式更具可读性:

which is far more readable than a single pattern:

"(0|[1-9]\\d|2[0-4]\\d|25[0-5])(\\.(0|[1-9]\\d|2[0-4]\\d|25[0-5])){3}"

请注意,这只是一个简单的示例:验证IP地址最好由 java.net 包中的类来完成,如果您愿意这样做,则模式应该放在方法之外并预先编译.

Note that this is just a quick example: validating IP addresses can probably better be done by a class from the java.net package, and if you'd do it like that, the pattern should be placed outside the method and pre-compiled.

请注意图案中的符号!

这篇关于我可以定义自定义字符类的简写吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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