簡體   English   中英

正則表達式,用於用Java中的僅大寫單詞拆分字符串

[英]Regular Expression for splitting a String by Upper Case only words in Java

我有這個...

 String bigWord = "I AM LOUD But also sensitive";
 String[] words = bigWord.split("[^A-Z| ]");

我希望該列表中的第一個條目為“我很大”,第二個條目為“但也敏感”。

上面的RegEx幾乎可以使用,但是它捕獲了第二個條目的第一個字母。

“我是大乙”

我該如何解決?

使用Matcher類,以便您輕松獲得組。

      String bigWord = "I AM LOUD But also sensitive";

      Pattern pattern = Pattern.compile("([A-Z ]+)? ([A-Z]?.*)");
      Matcher matcher = pattern.matcher(bigWord);
      while(matcher.find()){
         System.out.println(matcher.group(1));
         System.out.println(matcher.group(2));
      }

輸出:

I AM LOUD
But also sensitive

正則表達式中的關鍵是:

A group of uppercased words an space A group of mixed chars

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM