碰到个正则的难题2x^3+3x^4+5x^5匹配这个字符串我写了这个正则进行匹配((\\d)x\\^(\\d)\\+?)+?下面是代码
但打印出5x^5
5
5
public static void parse(String str)
{
String p="((\\d)x\\^(\\d)\\+?)+?";

Pattern pt=Pattern.compile(p);
Matcher m=pt.matcher(str);
if(m.matches())
{

int count=m.groupCount();
for(int i=1;i<=count;i++)
{
System.out.println(m.group(i));
}
}
}
怎么把所有的数字都匹配出来

解决方案 »

  1.   

    不是不会,是看不懂你要干什么
    问题如果描述不清楚,就给出例子对应的结果,这样免得大家去猜,也能够尽快得到答案是要全部匹配
    String str = "2x^3+3x^4+5x^5";
    String p="(\\dx\\^\\d\\+)*\\dx\\^\\d";        
    Pattern pt=Pattern.compile(p);
    Matcher m=pt.matcher(str);
    while(m.find())
    {
        System.out.println(m.group());
    }
    /*---------输出--------
    2x^3+3x^4+5x^5
    */还是要按组匹配,取得每一组
    String str = "2x^3+3x^4+5x^5";
    String p="\\dx\\^\\d";        
    Pattern pt=Pattern.compile(p);
    Matcher m=pt.matcher(str);
    while(m.find())
    {
         System.out.println(m.group());
    }
    /*---------输出--------
    2x^3
    3x^4
    5x^5
    */还是说连每一组的数字都要单独体现
    String str = "2x^3+3x^4+5x^5";
    String p="(\\d)x\\^(\\d)";        
    Pattern pt=Pattern.compile(p);
    Matcher m=pt.matcher(str);
    while(m.find())
    {
         for(int i=0;i<=m.groupCount();i++)
         {
             System.out.println(m.group(i));
         }
    }
    /*---------输出--------
    2x^3
    2
    3
    3x^4
    3
    4
    5x^5
    5
    5
    */
      

  2.   

    lxcnn 给的正则很强大……
      

  3.   

    楼上解释的很好了!
    我来解释下楼主的结果!
    for循环你是从1开始的,而第一个字符串才是全匹配的结果:System.out.println(m.group(i));==2x^3+3x^4+5x^5你从1开始输出的是最后一次所有自匹配匹配的内容:
    (\\d)x\\^(\\d)\\+?)  === 5x^5
    第一个(\\d)  匹配5x中的5
    第一个(\\d)  匹配^5中的5