有 Java 编程相关的问题?

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

java从字符串中删除字母数字单词

我正试图从字符串中删除字母数字单词

 String[] sentenceArray= {"India123156 hel12lo 10000 cricket 21355 sport news 000Fifa"};
    for(String s: sentenceArray)
        {
            String finalResult = new String();
            String finalResult1 = new String();
            String str= s.toString();
            System.out.println("before regex : "+str);
            String regex = "(\\d?[,/%]?\\d|^[a-zA-Z0-9_]*)";
            finalResult1 = str.replaceAll(regex, " ");
            finalResult = finalResult1.trim().replaceAll(" +", " ");
            System.out.println("after regex : "+finalResult);
        }

输出:hel lo板球运动新闻Fifa

但我需要的输出是:板球运动新闻

伙计们请帮帮我。。 提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    public static void main(String[] args) {
        String s = "India123156 hel12lo 10000 cricket 21355 sport news 000Fifa";
        // String s = "cricket abc";
        // cricket sport news
        System.out.println(s.replaceAll("\\b\\w+?[0-9]+\\w+?\\b", "").trim());
    
    }
    

    O/p:

    cricket  sport news
    
    Explaination :
    
    \\b  > word boudry i.e, it marks the beginning and end of a word..
    \\w+  >one or more alphabets . 
    \\w+?[0-9]  > Zero or one occurance of (one or more alphabets) followed by one or more digits.
    \\w+? > ending with  Zero or one occurance of (one or more alphabets) and marked by word boundry.
    trim()  > removing leading and trailing whitespaces.