2013-03-03 122 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