2016-02-28 88 views
2

我需要检查回文在一个单独的类,但忽略非字母字符。因此,例如,雷达将仍有资格,如果它被写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方法,或如何使用正则表达式

+0

标准的正则表达式无法检测回文(高达无限的价值)的东西是以前所接受。 http://stackoverflow.com/questions/233243/how-to-check-that-a-string-is-a-palindrome-using-regular-expressions但是有一些页面 –

+0

在一些实现可能可以做在Java类的正则表达式实现如图有些语言虽然,但他们在技术上都是不正规的 –

+0

[删除所有非字母字符(http://stackoverflow.com/questions/11149759/remove-all-non-alphabetic-characters-从-A-串阵列式-java的),并使用[定期回文校验码(http://stackoverflow.com/a/4138856/3832970)。请参阅[本演示](http://ideone.com/ALr1Sl)。它按预期工作吗? –

回答

2

您可以使用此模式与matches方法(如果你想匹配一个字母也一样,在末尾添加|[^a-z]*[a-z][^a-z]*

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

:如果你想添加不区分大小写选项)。

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方法,锚是隐含的。),因为它们需要内存

相关问题