开发者

How can I get all content between two pipes using regular expression

开发者 https://www.devze.com 2023-03-19 20:00 出处:网络
I have a String say String s = \"|India| vs Aus\"; In this case result should be only India. Second case :

I have a String say

String s = "|India| vs Aus";

In this case result should be only India.

Second case :

String s = "Aus vs |India|"; In this case result should be only India.

3rd case:

String s = "|India| vs |Aus|" Result shouls contain only India, Aus开发者_C百科. vs should not present in output.

And in these scenarios, there can be any other word in place of vs. e.g. String can be like this also |India| in |Aus|. and the String can be like this also |India| and |Sri Lanka| in |Aus|. I want those words that are present in between two pipes like India, Sri Lanka , Aus.

I want to do it in Java.

Any pointer will be helpful.


You would use a regex like...

\|[^|]+\| 

...or...

\|.+?\| 

You must escape the pipe because the pipe has special meaning in a regex as or.


You are looking at something similar to this:

    String s = "|India| vs |Aus|";
    Pattern p = Pattern.compile("\\|(.*?)\\|");
    Matcher m = p.matcher(s);
    while(m.find()){
        System.out.println(m.group(1));
    }

You need to use the group to get the contents inside the paranthesis in the regexp.

0

精彩评论

暂无评论...
验证码 换一张
取 消