我使用swing组件编写了一个基本的CLI,并使用Regex来识别命令.
我遇到过一些特殊的事情,我无法解释.我在这做错了什么?
这是我的代码:
class GraphCommandFactory {
private final GraphSearchController controller;
private final GraphSearchModel model;
private final ArrayList<Pattern> commands;
public GraphCommandFactory(GraphSearchController controller, GraphSearchModel model) {
this.model = model;
this.controller = controller;
this.commands = new ArrayList<>();
commands.add(Pattern.compile("SET START ([A-Z]{4,8})"));
}
public Command createCommand(String commandString) {
Command returnCommand;
// Test the string against each regex
int command = 0;
Matcher matcher = commands.get(command).matcher(commandString);
...
private String[] extractArguments(Matcher matcher) {
String[] arguments = new String[matcher.groupCount()];
for (int i = 0, j = matcher.groupCount(); i < j; i++) {
arguments[i] = matcher.group(i);
}
return arguments;
}
Run Code Online (Sandbox Code Playgroud)
extractArguments函数附带问题...使用模式(在Matcher中):
Pattern.compile("SET START ([A-Z]{4,8})"));
Run Code Online (Sandbox Code Playgroud)
输掉了最后一组.但是,如果我将其修改为:
Pattern.compile("SET START ([A-Z]{4,8})()"));
Run Code Online (Sandbox Code Playgroud)
然后它正确捕捉我想要的东西.
我是否误解了如何使用正则表达式,模式和匹配器?或者这是最后一个捕获组丢失的错误?
我使用Java SDK 1.8和Netbeans作为我的IDE.使用调试工具让我更加聪明.
问题出在你的for循环中:
for (int i = 0, j = matcher.groupCount(); i < j; i++) {
arguments[i] = matcher.group(i);
}
Run Code Online (Sandbox Code Playgroud)
因为你只是循环比1少 matcher.groupCount
将其更改为:
for (int i = 0; i <= matcher.groupCount(); i++) {
arguments[i] = matcher.group(i);
}
Run Code Online (Sandbox Code Playgroud)
根据Javadoc:
groupCount返回此匹配器模式中的捕获组数.组0表示按惯例的整个模式.它不包含在此计数中.
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |