Java:正则表达式不匹配 [英] Java: Regex not matching

查看:286
本文介绍了Java:正则表达式不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有逗号分隔的字符串值.每个字符串都可以包含字符或数字,以及-"或"/"或.".

I have comma separated string values. Every string may contain characters or numbers along with '-' or '/' or '.'.

我的代码如下:

final String VALUES_REGEX = "^\\{([0-9a-zA-Z\\-\\_\\.])+,*([0-9a-zA-Z\\-\\_\\.])*\\}$";
final Pattern REGEX_PATTERN = Pattern.compile(VALUES_REGEX);
final String values = "{df1_apx.fhh.irtrs.d.rrr, ffd1-afp.farr.d.rrr.asgd}";
final Matcher matcher = REGEX_PATTERN.matcher(values);
if (null != values && matcher.matches()) {
    // further logic
}
...
...

如果正则表达式匹配失败,则条件始终返回假值.我使用

Here if condition always returns false value because regex match fails. I verified regex using regexper. It looks fine.

你能告诉我这是怎么回事吗?

Can you please tell me what is wrong here?

更新:使用Avinash提供的正则表达式,匹配可以正常工作.但是寻找团体却失败了.代码如下:

Update: With regex provided by Avinash, match works. But finding of groups fails. Code looks like:

final String VALUES_REGEX = "^\\{([0-9a-zA-Z\\-\\_\\.])+,*\\s*([0-9a-zA-Z\\-\\_\\.])*\\}$";
final Pattern REGEX_PATTERN = Pattern.compile(VALUES_REGEX);
final String values = "{df1_apx.fhh.irtrs.d.rrr, ffd1-afp.farr.d.rrr.asgd}";
final Matcher matcher = REGEX_PATTERN.matcher(values);
if (null != values && matcher.matches()) {
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
}
...
...

更新:在Avinash提供新的正则表达式之后,尝试查找单独的组.但是逗号也被认为是字符串的一部分.代码如下:

Update: After new regex provided by Avinash, tried to find separate groups. But comma is also considered as part of string. Code looks like:

final String VALUES_REGEX = "^\\{([0-9a-zA-Z\\-\\_\\.]+)((?:,\\s*[0-9a-zA-Z\\-\\_\\.]*)*)\\}$";
final Pattern REGEX_PATTERN = Pattern.compile(VALUES_REGEX);
final String values = "{df1_apx.fhh.irtrs.d.rrr, ffd1-afp.farr.d.rrr.asgd}";
final Matcher matcher = REGEX_PATTERN.matcher(values);
if (null != values && matcher.matches()) {
    for (int index=1; index<=matcher.groupCount(); ++index) {
        System.out.println(matcher.group(index));
    }
}
...
...

输出为:

df1_apx.fhh.irtrs.d.rrr

, ffd1-afp.farr.d.rrr.asgd

我只需要找到匹配的字符串值.

I need to find only matching string values.

推荐答案

输入字符串中逗号后有一个空格.

There was a space after comma in your input string.

final String VALUES_REGEX = "^\\{([0-9a-zA-Z\\-\\_\\.]+)((?:,\\s*[0-9a-zA-Z\\-\\_\\.]*)*)\\}$";

这篇关于Java:正则表达式不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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