繁体   English   中英

Android检查字符串是否在单词之前包含数字

[英]Android check if string contains number before a word

我目前正在使用arraylist来存储一些文本,然后稍后检查该列表以查看其中是否包含某些单词并将其解析为数字。 例如,我的arraylist可能包含:

[cancel, port, 4.5, 3 min, 3/4 terminal]

我想解析3 min以获得3 我目前使用:

for (int i = 0; i < textArray.size(); i++) {
  if (textList.contains("min")
     number = Double.parseDouble(textList.get(i).replaceAll("[^0-9]", ""));
}

但是我遇到的问题是它将看到3 min ,并且还将看到3/4 terminal因为它包含min 有没有一种方法可以使用包含来确保单词恰好是min

代替contains()使用endsWith()

if (textList.endsWith(" min") {
    number = Double.parseDouble(textList.get(i).replaceAll("[^0-9]", ""));
}

如何检查字符串是否以数字开头,然后检查该字符串是否与单词min完全匹配?

    String[] strValues = {
        "cancel",
        "port",
        "4.5",
        "3 min",
        "3/4 terminal"
    };

    for(String str : strValues){

        if(str.matches("^[0-9].*$"))
            System.out.println(str + " starts with a number");
            String[] results = str.split("\\s+");
            Boolean matchFound = Arrays.asList(results).contains("min");
            System.out.println(str + " is a number that contains a the word min");
        else
            System.out.println(str + " does not start with a number");

    }

代码未经测试,但是应该为您提供要使用的内容。 尽管有其他人回答,但还有更好的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM