Jayce
Jayce

Reputation: 842

Android check if string contains number before a word

I am currently using an arraylist to store some text and then later checking that list to see if it contains certain words and parsing them for the numbers. For example my arraylist could contain:

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

And I want to parse the 3 min to get the number 3. I currently use:

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

But the issue I am having is that it will see the 3 min and it will also see the 3/4 terminal because it contains min. Is there a way to use contains to make sure the word is exactly min?

Upvotes: 0

Views: 104

Answers (2)

jamesc
jamesc

Reputation: 12837

How about checking if the string starts with a number and then checking if that string has an exact match for the word 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");

    }

Code is untested but it should give you what you asked for which was to use contains. There are better ways though as others have answered

Upvotes: 1

forpas
forpas

Reputation: 164089

Instead of contains() use endsWith():

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

Upvotes: 4

Related Questions