簡體   English   中英

Java String - 查看字符串是否僅包含數字和字符而不包含單詞?

[英]Java String - See if a string contains only numbers and characters not words?

我有一個字符串數組,我在我的應用程序中加載,它包含不同的單詞。 我有一個簡單的if語句,看它是否包含字母或數字但不包含單詞。

我的意思是我只想要那些像AB2CD5X這樣的AB2CD5X ...我想刪除所有其他單詞,如Hello 3 3 wordany other單詞,這是英語單詞。 除了那些包含真實語法單詞的單詞之外,是否可以只過濾alphaNumeric單詞。

我知道如何檢查字符串是否包含字母數字

Pattern p = Pattern.compile("[\\p{Alnum},.']*");

也知道

 if(string.contains("[a-zA-Z]+") || string.contains([0-9]+])

你需要的是英語單詞詞典。 然后你基本上掃描輸入並檢查字典中是否存在每個標記。 您可以在線查找字典條目的文本文件,例如Jazzy拼寫檢查器 您也可以檢查詞典文本文件

下面是一個示例代碼,假設您的字典是UTF-8編碼的簡單文本文件,每行只有一個(小寫)字:

public static void main(String[] args) throws IOException {
    final Set<String> dictionary = loadDictionary();
    final String text = loadInput();
    final List<String> output = new ArrayList<>();
    // by default splits on whitespace
    final Scanner scanner = new Scanner(text);
    while(scanner.hasNext()) {
        final String token = scanner.next().toLowerCase();
        if (!dictionary.contains(token)) output.add(token);
    }
    System.out.println(output);

}

private static String loadInput() {
    return "This is a 5gse5qs sample f5qzd fbswx test";
}

private static Set<String> loadDictionary() throws IOException {
    final File dicFile = new File("path_to_your_flat_dic_file");
    final Set<String> dictionaryWords = new HashSet<>();
    String line;
    final LineNumberReader reader = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(dicFile), "UTF-8")));
    try {
        while ((line = reader.readLine()) != null) dictionaryWords.add(line);
        return dictionaryWords;
    }
    finally {
        reader.close();
    }
}

如果您需要更准確的結果,則需要提取單詞的詞干 請參閱Apache的LuceneEnglishStemmer

您可以使用Cambridge Dictionaries來驗證人類的單詞。 在這種情況下,如果您找到“人類有效”字詞,則可以跳過它。

正如文檔所說,要使用庫,您需要初始化請求處理程序和API對象:

DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
SkPublishAPI api = new SkPublishAPI(baseUrl + "/api/v1", accessKey, httpClient);
api.setRequestHandler(new SkPublishAPI.RequestHandler() {
    public void prepareGetRequest(HttpGet request) {
        System.out.println(request.getURI());
        request.setHeader("Accept", "application/json");
    }
});

要使用“api”對象:

      try {
          System.out.println("*** Dictionaries");
          JSONArray dictionaries = new JSONArray(api.getDictionaries());
          System.out.println(dictionaries);

          JSONObject dict = dictionaries.getJSONObject(0);
          System.out.println(dict);
          String dictCode = dict.getString("dictionaryCode");

          System.out.println("*** Search");
          System.out.println("*** Result list");
          JSONObject results = new JSONObject(api.search(dictCode, "ca", 1, 1));
          System.out.println(results);
          System.out.println("*** Spell checking");
          JSONObject spellResults = new JSONObject(api.didYouMean(dictCode, "dorg", 3));
          System.out.println(spellResults);
          System.out.println("*** Best matching");
          JSONObject bestMatch = new JSONObject(api.searchFirst(dictCode, "ca", "html"));
          System.out.println(bestMatch);

          System.out.println("*** Nearby Entries");
          JSONObject nearbyEntries = new JSONObject(api.getNearbyEntries(dictCode,
                  bestMatch.getString("entryId"), 3));
          System.out.println(nearbyEntries);
      } catch (Exception e) {
          e.printStackTrace();
      }

Antlr可能會幫助你。 Antlr代表ANother語言識別工具

Hibernate使用ANTLR來解析其查詢語言HQL(如SELECT,FROM)。

if(string.contains("[a-zA-Z]+") || string.contains([0-9]+])

我認為這是一個很好的起點,但是因為你正在尋找包含字母和數字的字符串,你可能需要:

if(string.contains("[a-zA-Z]+") && string.contains([0-9]+])

我想你可能還想檢查是否有空格? 對? 因為你可以表明有單獨的單詞或某些序列,如3 word 所以也許最后你可以使用:

if(string.contains("[a-zA-Z]+") && string.contains([0-9]+] && !string.contains(" "))

希望這可以幫助

你可以試試這個,

首先使用帶有默認分隔符的StringTokenizer對字符串進行標記,如果每個標記僅包含數字或僅包含字符,則丟棄它,剩余的將是包含數字和字符組合的單詞。 僅用於識別數字,只能使用正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM