नियमित अभिव्यक्ति "[!._,'@?//s]" सभी विराम चिह्नों और स्पेस से मेल खाती है।
उदाहरण
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);
}
}
आउटपुट
Number of matches: 8
split() विधि String क्लास की एक नियमित अभिव्यक्ति को दर्शाने वाला मान स्वीकार करती है और वर्तमान स्ट्रिंग को टोकन (शब्दों) की सरणी में विभाजित करती है, दो मिलानों की घटना के बीच की स्ट्रिंग को एक टोकन मानती है।
उदाहरण के लिए, यदि आप इस विधि को डिलीमीटर के रूप में सिंगल स्पेस " " पास करते हैं और स्ट्रिंग को विभाजित करने का प्रयास करते हैं। यह विधि दो स्पेस के बीच के शब्द को एक टोकन मानती है और वर्तमान स्ट्रिंग में शब्दों (स्पेस के बीच) की एक सरणी वापस करती है।
इसलिए, हर स्पेस और विराम चिह्न पर स्ट्रिंग विभाजित करने के लिए, ऊपर निर्दिष्ट नियमित अभिव्यक्ति को पैरामीटर के रूप में पास करके इस पर split() विधि लागू करें।
उदाहरण
import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
public static void main(String args[]) {
String regex = "[!._,'@? ]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringTokenizer str = new StringTokenizer(input, regex);
while (str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
}
आउटपुट
Enter a string: This is!a.sample text,with punctuation!marks@and_spaces This is a sample text with punctuation marks and_spaces