Java正则表达式首先匹配 [英] Java regex first match only

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

问题描述

如何告知以下正则表达式只找到FIRST匹配?以下代码继续在字符串中查找所有可能的正则表达式。

How do I tell the following regex to only find the FIRST match? The following code keeps finding all possible regex within the string.

即。我只关注子串的索引(200-800; 50)

i.e. I'm looking only for the indices of the substring (200-800;50]

public static void main(String[] args) {

    String regex = "(\\[|\\().+(\\]|\\))";

    String testName=  "DCGRD_(200-800;50]MHZ_(PRE|PST)_(TESTMODE|REG_3FD)";

            Pattern pattern = 
            Pattern.compile(regex);

            Matcher matcher = 
            pattern.matcher(testName);

            boolean found = false;

            while (matcher.find()) {
                System.out.format("I found the text" +
                    " \"%s\" starting at " +
                    "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());
                found = true;

            }

            if (!found){
                System.out.println("Sorry, no match!");
            }
}


推荐答案

matcher.group(1)将返回第一个匹配。

如果你的意思是懒惰匹配而不是急切匹配,请尝试加一个?在正则表达式中的+之后。

If you mean lazy matching instead of eager matching, try adding a ? after the + in the regular expression.

或者,您可以考虑使用比。+ 更具体的内容来匹配括号之间的内容。如果你只是期待字母,数字和一些字符,那么可能像 [ - A-Z0-9; _。] + 会更好吗?

Alternatively, you can consider using something more specific than .+ to match the content between the brackets. If you're only expecting letters, numbers and a few characters then maybe something like [-A-Z0-9;_.]+ would work better?

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

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