简体   繁体   中英

How to read numbers after followed by particular Character of a string using Java Android?

String str = "[amt is E234.98.valid 23/12/2013.Sample text]"

如何仅从上述示例字符串中的字符“ E”之后读取量值。

You can use regexp and matching groups to extract what you need.

CODE update:

Use by calling ParseWithRegexp.testIt()

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

public class ParseWithRegexp {
    static String str = "[amt is E234.98.valid 23/12/2013.Sample text  E134.95.valid 23/12/2015]";
    public static void testIt() {
        Pattern p = Pattern.compile("E([0-9.]+)\\.valid");
        Matcher m = p.matcher(str);
        while (m.find()) {
            System.out.println("found: "+m.group(1));
        }
    }
}

Upadte: You can be more strict with the regexp, for example: "E([0-9]+\\\\.[0-9]+)"

You can use indexOf() method from String , for example:

If you only want what's in bold, and if you must have a dot in your number:

String str = "[amt is E 234.98 .valid 23/12/2013.Sample text]";

Do this:

String str = "whatever E2024.1.E";

///Start from the first character after "E"
int startPos = str.indexOf("E") + 1;

///Start from startPos
int dotPos = str.indexOf(".", startPos);

///Start from the first character after dotPos
int endPos = str.indexOf(".", dotPos + 1);

///return the result
return str.substring(startPos, endPos);

Otherwise, if you only want the numbers until the first dot do this:

String str = "whatever E2024.1.E";

///Start from the first character after "E"
int startPos = str.indexOf("E") + 1;

///Start from the first character after startPos
int endPos = str.indexOf(".", startPos+ 1);

///return the result
return str.substring(startPos, endPos);

The only difference is that if you must have a dot present, then you have to check its position and start from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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