Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find string pattern in Java

Tags:

java

string

regex

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.

like image 623
user1705636 Avatar asked Sep 28 '12 08:09

user1705636


People also ask

How do you find a pattern in the given string Java?

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.

How do you search a string for a pattern?

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.

What is string pattern in Java?

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.

What does matches () do in Java?

Java String matches() The matches() method checks whether the string matches the given regular expression or not.


1 Answers

    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));
    }
like image 162
Nishant Avatar answered Oct 25 '22 18:10

Nishant