In this example, I have shared Java regex program to split a string at every space and punctuation. The regular expression "[!._,'@?//s]"
matches all the punctuation marks and spaces.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main( String args[] ) { String input = "This is!a.sample"text,with punctuation!marks"; Pattern p = Pattern.compile("[!._,'@?//s]"); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } } |
Program Output
1 | Number of matches: 8 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.