简体   繁体   中英

How to find string pattern in Java

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 .

    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));
    }

Use a regular expression. In Java, you can use the Pattern class .

You could use regular expressions for that. Take a look at the classes Pattern and Matcher .

The regular expression you would use in that case would be:

\$\[.*?\]\$

Alternatively, you could work with String.indexOf and String.substr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM