Java字符串参数第一个/最后一个参数



我只是在学习,找不到以下任务的解决方案:

这就是任务:

编写一个函数,将任务作为字符串参数传递。我们限制自己在文本中搜索。每个任务的结构如下:

<TASK> <WHAT> <TEXT>

你应该能够搜索第一个和最后一个单词或字母:

<TASK> = "FIND (FIRST | LAST) (CHAR | WORD)"

输出应该始终是搜索开始的地方,否则为-1。

示例:

"FIND FIRST CHAR D This is a text" → Output: "0"
"FIND FIRST CHAR a This is a text" → Output: "-1"
"FIND FIRST CHAR s This is a text" → Output: "3"
"FIND LAST CHAR t This is a text" → Output: "16"
"FIND FIRST WORD is This is a text" → Edition: "5"
"FIND LAST WORD is This is a text" → Output: "5"

提示

  • 如果按Run,您将看到所有System.out.println的控制台输出
private static final Pattern PATTERN = Pattern.compile("FIND\s+(?<pos>FIRST|LAST)\s+(?<unit>CHAR|WORD)\s+(?<what>\S+)\s+(?<text>.+)");
public static int find(String str) {
Matcher matcher = PATTERN.matcher(str);
if (!matcher.matches())
return -1;
String pos = matcher.group("pos");
String unit = matcher.group("unit");
String what = matcher.group("what");
String text = matcher.group("text");
boolean first = "FIRST".equals(pos);
if ("CHAR".equals(unit))
return first ? text.indexOf(what) : text.lastIndexOf(what);
if ("WORD".equals(unit)) {
Matcher match = Pattern.compile("\b" + what + "\b").matcher(text);
int offs = -1;
while (match.find()) {
offs = match.start();
if (first)
break;
}
return offs;
}
return -1;
}

相关内容

最新更新