子串检查android的帮助

时间:2012-05-01 21:21:18

标签: android substring

有人可以帮助我一些代码,我有它应该检查传递的字符串是2字符串和3整数哪个工作正常,但如果1 int是零,它不起作用

所以,如果它是CM044它将无法工作,CM450将工作可以有人请帮助。

public boolean checkModule(String Module) {

    if(Module.length() == 5){
      boolean hasString = false;
      boolean hasInt = false;
      String letters = Module.substring(0, 2);
      Pattern p = Pattern.compile("^[a-zA-Z]+$");
      Matcher m = p.matcher(letters);
      if (m.matches()) {
        hasString = true;
      }
      String numbers=Module.substring(2,5);
      try {
        int num = Integer.parseInt(numbers);
        String n = num + "";
        if (num >0 && n.length() == 3)
            hasInt = true;
      } catch (Exception e) {
      }
      if (hasInt && hasString) {
        return true;
      }
     }else{
      return false;
     }

    return false;
}

由于

2 个答案:

答案 0 :(得分:1)

如果你打算使用正则表达式,你一定要坚持使用它们,而不是变化和变换。

package com.examples;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {


    /**
     * @param args
     */
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        String[] testInputs = new String[] {"CM045", "CM450"};

        for(String input : testInputs) {
            System.out.println("The module " + input + " is " + (checkModule(input) ? "valid" : "invalid"));
        }
    }

    public boolean checkModule(String Module){
        Pattern p = Pattern.compile("[A-Z]{2}[0-9]{3}");
        Matcher m = p.matcher(Module.toUpperCase());
        return m.matches();
    }

}

答案 1 :(得分:0)

如果字符串为“045”,则整数值为45,因此num的长度不能为3

使用此

if(num>=0) {
  hasInt = true;
}

它必须工作