- 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 match bold fields in a HTML script using a regular expression in Java?
The regular expression "\S" matches a non-whitespace character and the following regular expression matches one or more non space characters between the bold tags.
"(\S+)"
Therefore to match the bold fields in a HTML script you need to −
Compile the above regular expression using the compile() method.
Retrieve the matcher from the obtained pattern using the matcher() method.
Print the matched parts of the input string using the group() method.
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String[] args) { String str = "<p>This <b>is</b> an <b>example>/b> HTML <b>script</b>.</p>"; //Regular expression to match contents of the bold tags String regex = "<b>(\S+)</b>"; //Creating a pattern object //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(str); //Creating an empty string buffer while (matcher.find()) { System.out.println(matcher.group()); } } }
Output
<b>is</b> <b>example</b> <b>script</b>
Advertisements