- Trending Categories
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
Search and Replace with Java regular expressions
Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn.
A regular expression is a special sequence of characters that help you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.
The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static String REGEX = "dog"; private static String INPUT = "The dog says meow. " + "All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); //get a matcher object Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } }
Output
The cat says meow. All cats say meow.
- Related Articles
- Replace '*' with '^' with Java Regular Expressions
- Replace one string with another string with Java Regular Expressions
- Replace all words with another string with Java Regular Expressions
- Validate city and state with Java Regular Expressions
- Validate Phone with Java Regular Expressions
- Java Regular Expressions Tutorial
- Validate the ZIP code with Java Regular expressions
- Working with Matcher.start() method in Java Regular Expressions
- Working with Matcher.end() method in Java Regular Expressions
- Working with simple groups in Java Regular Expressions
- Validate the first name and last name with Java Regular Expressions
- Java regular expressions sample examples
- Possessive quantifiers Java Regular expressions
- Java Regular expressions Logical operators
- Reluctant quantifiers Java Regular expressions

Advertisements