gpt4 book ai didi

Java 正则表达式无法匹配一行注释

转载 作者:行者123 更新时间:2023-12-02 05:55:33 25 4
gpt4 key购买 nike

我正在为类 Java 语言编写一个编译器,需要为我的分词器匹配 //Comment. 样式的单行注释的出现次数。

我的尝试:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchOneLineComment {
public static void main(String[] args) {
Matcher matcher = Pattern.compile("//(.*)").matcher("//abc");
System.out.println(matcher.group()); // should print "//abc"... right?
}
}

但是我收到以下错误:

Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:485)
at java.util.regex.Matcher.group(Matcher.java:445)
at MatchOneLineComment.main(MatchOneLineComment.java:7)

任何帮助将不胜感激。

最佳答案

别忘了调用Matcher#find()

matcher.find();

并在调用group()之前检查结果。

来自 javadoc

Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

关于Java 正则表达式无法匹配一行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com