繁体   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