有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java查找字符串格式的数字中的字符

如何在数字中找到字符串

下面是一个简单的例子

private char check() {
        String sample ="1212kkk";//121hhh444 | 12-22
        return 'k';//'h' | '-'

    }

如果不是数字,我想返回那个值

我怎样才能从这个戒指上得到第一个角色


共 (6) 个答案

  1. # 1 楼答案

    我有什么不对劲吗?如果将某些内容保存为int(数字),则其中不能包含字符串值。但是,如果您的意思是,您有一个字符串,在它的字符串编号中,并且只想获取数字,那么这个regex命令将获取所有数字

    /(\d+)/
    
  2. # 2 楼答案

    试试番石榴

    CharMatcher.indexIn

    比如: if(CharMatcher.JAVA_LETTER.indexIn(yourString) != -1) return yourString.charAt(CharMatcher.JAVA_LETTER.indexIn(yourString));

    public static void main(String[] args) {
        String yourString = "123abc";
        int indexOfLetter = CharMatcher.JAVA_LETTER.indexIn(yourString);
        if (indexOfLetter != -1) {
            char charAt = yourString.charAt(indexOfLetter);
            System.out.println(charAt);
        }
    }
    

    打印a

  3. # 3 楼答案

    您需要更改方法的签名,否则调用方将无法判断字符串何时为“良好”(即仅包含数字)。一种方法是返回^{},它是char原语的包装器

    在内部,您可以使用简单的正则表达式[^0-9]来匹配String中的第一个非数字。当没有匹配项时,返回null。这样,调用者就可以像这样调用您的方法:

    private static Character check(String s) {
        Pattern firstNonDigit = Pattern.compile("[^0-9]");
        Matcher m = firstNonDigit.matcher(s);
        if (m.find()) {
            return m.group().charAt(0); // The group will always be 1 char
        }
        return null; // Only digits or no characters at all
    }
    ...
    Character wrongChar = check("12-34");
    if (wrongChar != null) {
        ...
    }
    
  4. # 4 楼答案

    试试这个:

    String result = sample.replaceAll("\\d" ,"");
    return result;
    
  5. # 5 楼答案

    private char check() {
        String sample ="1212kkk";//121hhh444 | 12-22
        return sample.replaceAll("[0-9]+", "").charAt(0);
    
    }
    
  6. # 6 楼答案

    \D是非数字,因此\D*是一行中任意数量的非数字。所以您的整个字符串应该匹配\D*

        Matcher m = Pattern.compile("\\D*").matcher(sample);
        while (m.find()) {
            System.err.println(m.group());
        }
    

    请用\\D*\D*试试