java比较前2个字符

时间:2012-09-27 07:28:17

标签: java

我想在文本中找到起始编号后跟。

example:
1.
11.
111.

我的x代码。 (x是数字)这是有效的。问题是当x超过2位数时。

x= Character.isDigit(line.charAt(0));
if(x)
if (line.charAt(1)=='.')

如何扩展此逻辑以查看x是否为整数,后跟。

我的第一个问题是: 我需要喜欢给定的行有x。格式与否,其中x是整数

5 个答案:

答案 0 :(得分:4)

您可以使用正则表达式[0-9]\.查看字符串中是否存在数字后跟句点。

如果您需要确保模式始终位于字符串的开头,则可以使用^[0-9]+\.

答案 1 :(得分:1)

您可以使用正则表达式:

Pattern.compile("C=(\\d+\\.\\d+)")

然而,更一般的是:

Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")

现在使用Pattern,您可以执行以下操作:

Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?");
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// Check all occurances
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " ");
    System.out.println(matcher.group());
}

答案 2 :(得分:1)

为什么不使用正则表达式?

([0-9]+)[.]

答案 3 :(得分:1)

public class ParsingData {
public static void main(String[] args) {
    //String one = "1.";
    String one = "11.";

    int index = one.indexOf(".");

    String num = (String) one.subSequence(0, index);

    if(isInteger(num)) {
            int number = Integer.parseInt(num);
            System.out.println(number);
    }
    else 
        System.out.println("Not an int");
}

public static boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
}

答案 4 :(得分:1)

编辑:糟糕,误读。

试试这个:

    public static boolean prefix(String s) {
        return s.matches("[0-9]+\\.");
    }
相关问题