gpt4 book ai didi

java - 在文件的每一行中查找有效模式

转载 作者:行者123 更新时间:2023-12-05 04:47:36 24 4
gpt4 key购买 nike

以下是我要解决的问题:

Write a program/script to count and print lines which have thefollowing pattern

Any 4 char sequence which has a pair of two different charactersfollowed by the reverse of that pair e.g xaax or raar. The string isnot considered valid if the pattern above exist in square brackets.

以下是一种可行的简单方法:

private static boolean hasValidPattern(String line) {
for (int i = 0; i < line.length()-3; i++) {
char first = line.charAt(i);
char second = line.charAt(i + 1);
char third = line.charAt(i + 2);
char fourth = line.charAt(i + 3);
if (first == fourth && second == third) {
if ( (i - 1) >= 0
&& line.charAt(i - 1) == '['
&& (i + 4) < line.length() &&
line.charAt(i + 4) == ']')
continue;
else
return true;
}
}
return false;
}

我想知道是否有更简洁的方法来做到这一点。可能使用正则表达式或其他东西。

最佳答案

使用正则表达式的简单解决方案如下:

private static boolean hasValidPattern(String line)
{
return line.matches(".*?(.)(?!\\1)(.)\\2\\1(?:(?!\\])|(?<!\\[.{4})).*");
}

图案解释:

  • .*? - 零个或多个字符(尽可能少)。

  • (.) - 匹配一个角色并将其捕获到第 1 组。

  • (?!\\1) - 后面没有相同的字符。

  • (.) - 匹配第二个字符并将其捕获到第 2 组中。

  • \\2\\1 - 将第 2 组中捕获的内容与第 1 组中捕获的内容进行匹配。

  • (?:(?!\])|(?<!\[.{4})) - 断言前 4 个字符括在方括号中。

  • .* - 零个或多个字符(尽可能多;即,直到行尾)。

Regex demo - Java demo .

关于java - 在文件的每一行中查找有效模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68416976/

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