请教各位一个问题:有一个字符串“127 (F3 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1 ) ”,我想取Y前面数字的和应该如何去做啊?Y前面的内容是变化的,也有可能是(F10 A8 Y1......)等等,所以要取前面的数字之和,10+8

解决方案 »

  1.   


    package xy;import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class qh { /**
     * @param args
     */
    public static void main(String[] args) {
    String str = "127 (F3 P3 A67 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1 )";
    int indexOfY = str.indexOf("Y");
    str = str.substring(0, indexOfY); Pattern p = Pattern.compile("[A-Z]([0-9]+)\\b");
    Matcher m = p.matcher(str);
    int sum = 0; while (m.find()) {
    sum += Integer.valueOf(m.group(1));
    }
    System.out.println(sum);
    }}
      

  2.   


            int rs = 0;
            String s = "127 (F3 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1 )";
            String[] array= s.replaceAll("Y.+", "").replaceAll("[^0-9]", " ").split("\\s+");
            for (int i = 0; i < array.length; i++) {
                if (!array[i].isEmpty()) {
                    rs += Integer.parseInt(array[i]);
                }
            }
            System.out.println(rs);
      

  3.   

    用shell搞看看:echo "127 (F3 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1)" | awk '{print $2, $3}' | sed 's/[^0-9]/ /g' | awk '{for(i=1; i<=NF; i++) sum += $i} END{print sum}'
      

  4.   

    用shell搞看看:echo "127 (F3 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1)" | awk '{print $2, $3}' | sed 's/[^0-9]/ /g' | awk '{for(i=1; i<=NF; i++) sum += $i} END{print sum}'
      

  5.   


    public class AA {
    public static void main(String[] args) {
    String str="127 (F11 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1 )" ;
    int index= str.indexOf('Y');
    int sum=0;
    String[] str1=str.substring(0, index).split("[\\D]+");
    System.out.println(str1.toString());
    for(int i=0;i<str1.length;i++){
    System.out.println(str1[i]);
    sum+=Integer.parseInt(str1[i]);
    }
    System.out.println(sum);
    }
    }
      

  6.   

    String str = "127 (F3 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1 )";
    String strs[] = str.replaceAll("[^0-9]+", "_").split("_");
    int result = Integer.parseInt(strs[1])+Integer.parseInt(strs[2]);
      

  7.   


    public static void main(String[] args) throws Exception{
    String s = "127 (F3 P3 Y9 K11 M1 R2 S42 V2 X5 Q33 U15 I1 )";
    Matcher m = Pattern.compile("\\((([a-zA-Z]{1}(\\d+)\\s*)+)Y.+?\\)").matcher(s);
    while(m.find()){
    String str = m.group(1);
    m = Pattern.compile("[a-zA-Z]{1}(\\d+)").matcher(str);
    while(m.find()){
    System.out.println(m.group(1));
    }
    }
    }