Java正则表达式和模式匹配:在模式中找到不包含它们的"空白"?

PLB*_*PLB 5 java regex pattern-matching

所以,我需要编写一个编译扫描器来做作业,并认为使用正则表达式是"优雅的".事实是,我以前很少使用它们,这是很久以前的事了.所以我忘了关于他们的大部分内容,需要环顾四周.我成功地使用它们作为标识符(或者至少我认为如此,我仍然需要做一些进一步的测试,但是现在它们看起来都很好),但我对数字识别有问题.

该函数nextCh()读取输入上的下一个字符(lookahead char).我想在这里做的是检查这个字符是否与正则表达式匹配[0-9]*.我在str当前令牌的字段中追加每个匹配的字符,然后我读取该字段的int值.它识别单个数字输入,例如"123",但我遇到的问题是输入"123 456",最后的str将是"123 456",而我应该得到2个单独的标记,字段为"123"和" 456" .为什么匹配?

private void readNumber(Token t) {
    t.str = "" + ch; // force conversion char --> String
    final Pattern pattern = Pattern.compile("[0-9]*");
    nextCh(); // get next char and check if it is a digit
    Matcher match = pattern.matcher("" + ch);
    while (match.find() && ch != EOF) {
        t.str += ch;
        nextCh();
        match = pattern.matcher("" + ch);
    }
    t.kind = Kind.number;
    try {
        int value = Integer.parseInt(t.str);            
        t.val = value;          
    } catch(NumberFormatException e) {
        error(t, Message.BIG_NUM, t.str);           
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!

PS:我确实使用下面的代码解决了我的问题.不过,我想了解我的正则表达式中缺陷的位置.

    t.str = "" + ch;
    nextCh(); // get next char and check if it is a number
    while (ch>='0' && ch<='9') {
        t.str += ch;
        nextCh();
    }
    t.kind = Kind.number;
    try {
        int value = Integer.parseInt(t.str);            
        t.val = value;          
    } catch(NumberFormatException e) {
        error(t, Message.BIG_NUM, t.str);           
    }
Run Code Online (Sandbox Code Playgroud)

编辑:结果我的正则表达式也不适用于标识符识别(再次,包括空白),所以我不得不切换到类似于我的"解决方案"的系统(虽然有很多条件).我猜我需要再次研究正则表达式:O

Ian*_*ird 1

你应该使用matches方法而不是find方法。从文档中:

matches 方法尝试将整个输入序列与模式进行匹配

find 方法扫描输入序列,查找与模式匹配的下一个子序列。

换句话说,通过使用find,如果字符串在任何地方包含matches数字,您都会得到一个匹配项,但如果您使用整个字符串,则必须与该模式匹配。

例如,试试这个:

Pattern p = Pattern.compile("[0-9]*");
Matcher m123abc = p.matcher("123 abc");
System.out.println(m123abc.matches());  // prints false
System.out.println(m123abc.find());     // prints true
Run Code Online (Sandbox Code Playgroud)