【问题标题】:How can I ignore spaces, punctuation marks, and all characters different than letters while checking a palindrome?在检查回文时,如何忽略空格、标点符号和所有不同于字母的字符?
【发布时间】:2016-02-28 22:12:21
【问题描述】:

我需要检查一个单独的类中的回文,但忽略非字母字符。例如,如果雷达写成 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 方法,或者如何使用正则表达式

【问题讨论】:

标签: java regex string palindrome


【解决方案1】:

您可以将此模式与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 方法,锚点是隐式的。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 2018-01-14
    相关资源
    最近更新 更多