现有段字符串:<a 1="fdgdgd" 2="sdfg" 3="sfg">要把其中的 1="fdgdgd", 2="sdfg", 3="sfg"
这三段提取出来写了个正则:<a(\s[0-9]+="[a-z]+")+>为什么总只能匹配最后一个 3="sfg",前两个匹配不到regexbuddy 中显示:
   Note: You repeated the capturing group itself.  The group will capture only the last iteration.  Put a capturing group around the repeated group to capture all iterations
网上查了下,说是要这样:<a((\s[0-9]+="[a-z]+")+)>
不过好像还是不行请问下该怎么写?

解决方案 »

  1.   


    package com.ex;import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test { /**
     * @param args
     */
    public static void main(String[] args) {
    String pat = "<a(\\s[0-9]+=\"[a-z]+\")+>";
            String str1 = "<a 1=\"fdgdgd\" 2=\"sdfg\" 3=\"sfg\">";
            Pattern ptn = Pattern.compile("[0-9]+=\"[a-z]+\"");        Matcher mat = ptn.matcher("<a 1=\"fdgdgd\" 2=\"sdfg\" 3=\"sfg\">");        while (mat.find()){
              System.out.println("Match: " + mat.group());
          }
    }}结果:Match: 1="fdgdgd"
    Match: 2="sdfg"
    Match: 3="sfg"
      

  2.   

     String str1 = "<a 1=\"fdgdgd\" 2=\"sdfg\" 3=\"sfg\">";你把人家的字符串都给改了,加上了反斜杠。。
      

  3.   


    String str = "<a 1=\"fdgdgd\" 2=\"sdfg\" 3=\"sfg\">";
    Pattern p = Pattern.compile("(?:\\d)([.[^\\d>]]+)");
    Matcher m = p.matcher(str);
    while(m.find()) {
    System.out.println(m.group());
    }结果:
    1="fdgdgd" 
    2="sdfg" 
    3="sfg"
      

  4.   

    上面的会拿出所有的(\s[0-9]+="[a-z]+"),我猜这个楼主也能做到,楼主的意思应该是要拿<a 1="fdgdgd" 2="sdfg" 3="sfg">里面的,比如有输入字符串:
    <b 4="fdgdgd"> 5="sdfg"<a 1="fdgdgd" 2="sdfg" 3="sfg"> 6="sfg"
    只要1、2、3,不要4、5、6如果我没猜错的话,这个正则可以这样写:
    (<a|\G)(\s[0-9]+=\"[a-z]+\")