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

时间:2014-12-05 00:26:39

标签: java regex output delimiter identifier

有没有办法以返回标识符的方式使用分隔符,例如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);

由于

2 个答案:

答案 0 :(得分:1)

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

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

编辑:还要注意,"字符" class通常包括(和#34;非单词字符"排除)下划线。因此,foo_bar_1在这个意义上将是一个有效的关键字。如果您不想这样做,请分别用\\W\\w替换[^A-z\\d][A-z\\d]

答案 1 :(得分:0)

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