

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Splitting the text using java.util.regex package
The split() method of the String class accepts a regular expression, splits the current input text into tokens and returns them as a string array.
Example
import java.util.Scanner; public class Example{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String[] strArray = input.split("\\d"); for (int i=0; i<strArray.length; i++) { System.out.println(strArray[i]); } } }
Output
Enter input text: 1Ramu 2Raju 3Radha 4Rahman 5Rachel Ramu Raju Radha Rahman Rachel
Splitting a string using Java.util.regex package −
Example
You can also spilt a String using the split() method of the patter class. this method accepts a string and splits it into tokens based on the underlying regular expressions and returns them as a string array.
import java.util.Scanner; import java.util.regex.Pattern; public class SplittingString{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "\\d"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); String[] strArray = pattern.split(input); for (int i=0; i<strArray.length; i++) { System.out.println(strArray[i]); } } }
Output
Enter input text: 1Ramu 2Raju 3Radha 4Rahman 5Rachel Ramu Raju Radha Rahman Rachel
- Related Questions & Answers
- Using a regex with text search in MongoDB
- Date format validation using Java Regex
- Matching Nonprintable Characters using Java regex
- Regex metacharacters in Java Regex
- How to match the beginning of the input using Java RegEx?
- How to match end of the input using Java RegEx?
- How to access Java package from another package
- How to match word characters using Java RegEx?
- How to match word boundaries using Java RegEx?
- How to match any character using Java RegEx
- How to convert python regex to java regex?
- How to install the Nuget Package using PowerShell?
- How to uninstall the MSI package using PowerShell?
- How to match digits using Java Regular Expression (RegEx)
- How to match non-word boundaries using Java RegEx?
Advertisements