【问题标题】:Java String - See if a string contains only numbers and characters not words?Java String - 查看字符串是否仅包含数字和字符而不包含单词?
【发布时间】:2014-07-17 15:20:52
【问题描述】:

我在整个应用程序中加载了一个字符串数组,其中包含不同的单词。我有一个简单的 if 语句来查看它是否包含字母或数字而不是单词。

我的意思是我只想要那些像 AB2CD5X .. 这样的词,我想删除所有其他词,比如 Hello 33 wordany other 是英文单词。除了那些包含真正语法词的词之外,是否可以只过滤字母数字词。

我知道如何检查字符串是否包含字母数字单词

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

也知道

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

【问题讨论】:

  • 简答:使用正则表达式
  • 你将如何识别一系列字母和一个单词之间的区别?
  • 这是我的问题 hirak?
  • 对于完整英语的真正语法词,您需要大量实施。只需检查用户输入的字母数字并将它们添加到键值对样式并消除其他内容。对于字母数字使用正则表达式

标签: java string filter


【解决方案1】:

你可以试试这个,

首先使用带有默认分隔符的StringTokenizer对字符串进行标记,对于每个标记,如果它仅包含数字或仅包含字符,则丢弃它,剩下的将是包含数字和字符组合的单词。为了仅识别数字字符,您可以使用正则表达式。

【讨论】:

    【解决方案2】:

    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(" "))

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您可以使用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();
            }
      

      【讨论】:

        【解决方案4】:

        你需要的是一本英语单词词典。然后你基本上扫描你的输入并检查你的字典中是否存在每个标记。 您可以在线查找字典条目的文本文件,例如Jazzy spellchecker。您也可以查看Dictionary text file

        这是一个示例代码,假设您的字典是一个简单的 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();
            }
        }
        

        如果需要更准确的结果,需要提取stems of your words。见Apache's LuceneEnglishStemmer

        【讨论】:

          【解决方案5】:

          Antlr 可能会对您有所帮助。 Antlr 代表 ANother Tool for Language Recognition

          Hibernate 使用 ANTLR 解析其查询语言 HQL(如 SELECT、FROM)。

          【讨论】:

            猜你喜欢
            • 2022-01-04
            • 1970-01-01
            • 1970-01-01
            • 2014-01-25
            • 2013-12-04
            • 2010-12-19
            • 2017-09-11
            相关资源
            最近更新 更多