gpt4 book ai didi

java - 检查回文时如何忽略空格、标点符号和所有不同于字母的字符?

转载 作者:行者123 更新时间:2023-11-30 08:40:25 26 4
gpt4 key购买 nike

我需要在单独的类中检查回文但忽略非字母字符。因此,例如,雷达如果写成 r,a,d,a,r 仍然符合条件

我相信我可以使用正则表达式,但我不知道如何使用。

这是我目前所拥有的,

 public static boolean isNonAlpha(char c) {
return (c == '-' || c == '.' || c == ' ' || c == ')' || c == '(') || c == '<' || c == '>' || c == ',';
}

public static String checkInput(String test){
int startChar = 0;
int endChar = test.length() - 1;
while (startChar < endChar) {
if (test.charAt(startChar) != test.charAt(endChar)) {
System.out.println("Your word is not a palindrome.");
System.exit(0);
} else {
if (test.charAt(startChar) == test.charAt(endChar))
startChar++;
endChar--;
}
}
System.out.println("Your word is indeed a palindrome.");
return test;

}

我卡在了如何合并我的 isNonAlpha 方法,或者如何使用正则表达式上

最佳答案

您可以将此模式与 matches 方法一起使用(如果需要,请添加不区分大小写的选项):

(?:[^a-z]*([a-z])(?=.*(\1[^a-z]*\2?+)$))+[^a-z]*[a-z]?[^a-z]*\2

如果您也想匹配单个字母,请在末尾添加 |[^a-z]*[a-z][^a-z]*

demo regexplanet (Java)
demo regex101

详情:

想法是从第 1 组中的字符串开头逐个捕获每个字母,并在前瞻中每次检查末尾是否存在相同的字母。捕获组 2 处于超前并在字符串末尾捕获它自己的内容(来自先前的重复)和新字母。在每次重复时,捕获组 2 会随着新字母(以及其他非字母字符)而增长。

(?: # repeated non capturing group
[^a-z]* # eventual other character before a letter
([a-z]) # the letter is captured in group 1
(?= # lookahead (to check the end of the string)
.*
(
\1 # backreference capture group1: the letter at the beginning
[^a-z]* # other characters
\2?+ # backreference capture group2: optional but possessive
# (that acts like a kind of conditional: if the group 2 already
# exists, it matches, otherwise not)
)
$ # anchor for the end of the string
)
)+
[^a-z]*[a-z]?[^a-z]* # an eventual letter in the middle
\2 # backreference capture group 2

(使用 matches 方法, anchor 是隐式的。)

关于java - 检查回文时如何忽略空格、标点符号和所有不同于字母的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688948/

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