android的子字符串检查帮助

android的子字符串检查帮助,android,substring,Android,Substring,有人能帮我写一些代码吗?我的代码应该是检查传递的字符串是2个字符串和3个整数,这很好,但是如果1个整数是零,它就不起作用了 所以,如果它是CM044,它将不起作用,CM450将起作用。请有人帮助 public boolean checkModule(String Module) { if(Module.length() == 5){ boolean hasString = false; boolean hasInt = false; String l

有人能帮我写一些代码吗?我的代码应该是检查传递的字符串是2个字符串和3个整数,这很好,但是如果1个整数是零,它就不起作用了

所以,如果它是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;
}
谢谢

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

用这个

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

如果你要使用正则表达式,你必须坚持使用它们,而且不能前后变化

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(); } } 包com.examples; 导入java.util.regex.Matcher; 导入java.util.regex.Pattern; 公共班机{ /** *@param args */ 公共静态void main(字符串[]args){ 新的Main(); } 公用干管(){ 字符串[]testInputs=新字符串[]{“CM045”、“CM450”}; for(字符串输入:testInputs){ System.out.println(“模块”+输入+”为“+”(检查模块(输入)?“有效”:“无效”); } } 公共布尔校验模块(字符串模块){ Pattern p=Pattern.compile(“[A-Z]{2}[0-9]{3}”); Matcher m=p.Matcher(Module.toUpperCase()); 返回m.matches(); } }
如果这是学校作业,请加上“家庭作业”标签。你比我快。但我会将正则表达式修改为:“[A-Z]{2}[1-9]{1}[0-9]{2}”,因为数字部分不能以0开头。我认为他的措辞很难理解,但在我看来,他似乎希望CM045有效,而他的代码,因为int解析,正在使其无效,因为它删除了前导0,因此无法显示为长度为3的int。此外,我对正则表达式的评论可能需要进行推理。正则表达式功能强大,但它们确实需要创建和执行引擎。因此,明智的做法是在一次运行中完成所有检查,而不是运行一个表达式,然后再执行该表达式本可以为您完成的更多检查。我在前面尝试过这一次,因为我注意到>但它仍然不起作用。