2013-03-03 77 views
0

我正在使用正则表达式显示当我需要它在正确的显示时做的麻烦。 现在我有这个代码,这是一个简单易用的正则表达式,但我仍然不明白它是如何工作的。有没有办法将字符串过滤为仅显示大写字母?第一次正则表达式用户

比方说,我在名字中的长句输入:

泰勒肖恩·卡西乔恩·彼得。

如果我不知道字符串中可能包含什么名字,我将如何获取字符串以仅显示一个名称? (说这是一个随机的名字将每次在填写)

import java.io.Console; 
import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Regex { 


    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     System.out.println("Enter your Regex: "); 
     Pattern pattern = 
     Pattern.compile(input.nextLine()); 


     System.out.println("Enter String to Search"); 
     Matcher matcher = 
     pattern.matcher(input.nextLine()); 

     boolean found = false; 
     while (matcher.find()) { 
      System.out.println("I found the text" + " " + matcher.group() +" starting at " + "index " + matcher.start() + " and ending at index " + matcher.end()); 
      found = true; 
     } 

     if (!found) { 
      System.out.println("No match found."); 
     } 
    } 

} 
+2

所以现在的问题是'如何匹配“泰勒肖恩·卡西乔恩·彼得字“'? '\ w +'可以做。 – Qtax 2013-03-03 03:40:42

+0

如果我们假设名字以大写字母开头,然后只以小写字母继续,那么您可以为名称构建一个模式。 – 2013-03-03 03:50:52

回答

1

您可以使用ranges inside character sets

[A-Z][a-z]* 

这意味着大写字母,其次是零个或多个小写字母

See it in action


如果你不满足于仅ASCII字母,您可以使用:

\\p{Upper}\\p{Lower}* 
+0

值得注意的是,这只能匹配ASCII字母。例如,它不会匹配像“René”这样的名称(只有“Ren”将被匹配)。 – 2015-12-09 20:05:01

+1

@BartKiers,公平点。更新了我的答案。 – ndn 2015-12-09 20:26:40

相关问题