In this example, we will see how to write a program to split a string by capital letters in Java.
Java Program to split string by Capital Letters
To split a string by capital letters, we will use (?=\\p{Lu})
regex. We will pass this regex in Java String split() method as shown in the following program.
\p{Lu}
is a shorthand for\p{Uppercase Letter}
. This regex matches uppercase letter.- Similarly
\p{Ll}
is a shorthand for\p{Lowercase Letter}
. This regex matches lowercase letter.
Source Code:
public class JavaExample{ public static void main(String args[]){ //a string with some capital letters String str = "IWantToSplitThisString"; //split string by capital letters String[] strArray = str.split("(?=\\p{Lu})"); //print substrings for(String s:strArray){ System.out.println(s); } } }
Output:
Main Article: Java String class