接受标识符中的数字但不接受独立数字的分隔符



有没有办法使用分隔符,返回标识符,例如 name1,但忽略数字 1,这样给定"name1 = 1",将只返回 name1 而不是 1。 目前,我正在使用.useDelimiter("[^A-Za-z0-9]+")。 这允许返回 name1,但也返回给定文件中数字的所有实例。 这被用来构建标识符字典。

while((sourceInput = sourceFile.readLine()) != null){
      String[] dictionaryWords = sourceInput.split("\W+");
      //ignores white space
      if(sourceInput.equals(""))
        continue;
      if(!sourceInput.contains("//")&&!sourceInput.contains(""")){//&&!sourceInput.contains(".")){
      for(String dWord: dictionaryWords){
        //replaces periods and commas with blank space, trims white space, and calls toLowerCase
        dWord = dWord.replace(".","");
        dWord = dWord.replace(",","");
        dWord = dWord.trim();
        dWord = dWord.toLowerCase();
        //delimiter call and searches for instances of letters and words
        Scanner remSpace = new Scanner(dWord);
        remSpace.useDelimiter("[a-zA-Z]+\d+");
        //while loop and successive if loops for creating the dictionary (key, int)
        while(remSpace.hasNext()){
          String resTreeInp = remSpace.next();  
          if(reservedTree.find(resTreeInp) == null){
            if(dictionary.containsKey(resTreeInp)){
            dictionary.put(resTreeInp, (int)dictionary.get(resTreeInp) + 1);//loop to avoid nullPointerException
          }
             else{
               dictionary.put(resTreeInp, 1);

谢谢

我猜你使用的是扫描仪?虽然可以做你想做的事(我认为,像"[\W\d]+(?=[A-z])"这样的东西应该有效 - 它的意思是"至少一个非单词字符,或一个数字,后跟一个字母"),但它可能不是最清晰/最优雅的解决方案。你为什么不简单地一行一行地阅读,然后用类似的东西从中获取你的标识符:

Pattern p = Pattern.compile("[A-z]\w+");
Matcher m = p.matcher(line);
while(m.find()) { doThisKeyword(m.group(0)); }

编辑:另请注意,"单词字符"类通常包括(并且"非单词字符"不包括)下划线。因此,从这个意义上说,foo_bar_1将是一个有效的关键字。如果不希望这样做,请分别将\W和 d \w替换为 [^A-z\d][A-z\d]

在数字之前至少需要一个字母表。所以正则表达式应该是"[a-zA-Z]+\d+"的.

最新更新