- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to print all the characters of a string using regular expression in Java?
The meta character "." matches all the characters, to print all the characters using the regular expressions −
Compile the regular expression using the compile() method.
Create a Matcher object using the matcher() method.
Find the matches using the find() method and for every match print the matched contents (characters) using the group() method.
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { //Regular expression to match a string of non-word with length 2 to 6 String regex = "."; Scanner sc = new Scanner(System.in); System.out.println("Enter your input string: "); String input = sc.nextLine(); //Creating a Pattern object Pattern p = Pattern.compile(regex); //Creating a Matcher object Matcher m = p.matcher(input); while(m.find()) { System.out.println(m.group()); } } }
Output
Enter your input string: This is a sample text T h i s i s a s a m p l e t e x t
Advertisements