Here is a string like this in Java.
String string="abc$[A]$def$[B]$ghi";
I want to search words that are located in $[*]$
pattern. The result of above the string is A
, B
.
Java provides the java. util. regex package for pattern matching with regular expressions. You can then search for a pattern in a Java string using classes and methods of this packages.
With RegEx you can use pattern matching to search for particular strings of characters rather than constructing multiple, literal search queries. RegEx uses metacharacters in conjunction with a search engine to retrieve specific patterns. Metacharacters are the building blocks of regular expressions.
The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern.
Java String matches() The matches() method checks whether the string matches the given regular expression or not.
String s = "abc$[A]$def$[B]$ghi";
Pattern p = Pattern.compile("\\$\\[.*?\\]\\$");
Matcher m = p.matcher(s);
while(m.find()){
String b = m.group();
System.out.println(">> " +b.substring(2, b.length()-2));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With