如何迭代正则表达式 [英] How to iterate over regex expression

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

问题描述

假设我有以下字符串:

name1=gil;name2=orit;

我想查找 name = value 并确保整个字符串与模式匹配。

I want to find all matches of name=value and make sure that the whole string matches the pattern.

所以我做了以下事情:


  1. 确保整个模式符合我的要求。

  1. Ensure that the whole pattern matches what I want.

Pattern p = Pattern.compile("^((\\w+)=(\\w+);)*$");
Matcher m = p.matcher(line);
if (!m.matches()) {
    return false;
}


  • 迭代模式 name = value

    Pattern p = Pattern.compile("(\\w+)=(\\w+);");
    Matcher m = p.matcher(line);
    while (m.find()) {
        map.put(m.group(1), m.group(2));
    }
    


  • 有没有办法使用一个正则表达式执行此操作?

    Is there some way to do this with one regex?

    推荐答案

    您可以通过以下方式验证并迭代匹配一个正则表达式:

    You can validate and iterate over matches with one regex by:


    • 确保匹配之间没有不匹配的字符(例如 name1 = x ;; name2 = y; )在我们的正则表达式的开头放一个 \G ,这意味着上一场比赛结束

    • Ensuring there are no unmatched characters between matches (e.g. name1=x;;name2=y;) by putting a \G at the start of our regex, which mean "the end of the previous match".

    通过将字符串的长度与 Matcher.end() ,它返回最后一个字符匹配后的偏移量。 / p>

    Checking whether we've reached the end of the string on our last match by comparing the length of our string to Matcher.end(), which returns the offset after the last character matched.

    类似于:

    String line = "name1=gil;name2=orit;";
    Pattern p = Pattern.compile("\\G(\\w+)=(\\w+);");
    Matcher m = p.matcher(line);
    int lastMatchPos = 0;
    while (m.find()) {
       System.out.println(m.group(1));
       System.out.println(m.group(2));
       lastMatchPos = m.end();
    }
    if (lastMatchPos != line.length())
       System.out.println("Invalid string!");
    

    现场演示

    某些语言可能允许您直接从
    $迭代各个匹配项b $ b ^((\\\\ + +)=(\\\\ + +);)* $ ,但我不相信你能用Java做到这一点。

    Some languages might allow you to iterate over the individual matches directly from
    ^((\\w+)=(\\w+);)*$, but I don't believe you can do this in Java.

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

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