简体   繁体   English

如何使用正则表达式获取两个管道之间的所有内容

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

I have a String say我有一个字符串说

String s = "|India| vs Aus"; String s = "|India| vs Aus";

In this case result should be only India .在这种情况下,结果应该只有India

Second case:第二种情况:

String s = "Aus vs |India|";字符串 s = "澳大利亚 vs |印度|"; In this case result should be only India .在这种情况下,结果应该只有India

3rd case:第三种情况:

String s = "|India| vs |Aus|"字符串 s = "|印度| vs |澳大利亚|" Result shouls contain only India, Aus .结果应该只包含India, Aus vs should not present in output. vs 不应该出现在 output 中。

And in these scenarios, there can be any other word in place of vs. eg String can be like this also |India|在这些场景中,可以有任何其他词来代替 vs。例如,字符串也可以是这样的 |India| in |Aus|.在|澳大利亚|。 and the String can be like this also |India|字符串也可以是这样的 |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.我想在 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 .您必须转义 pipe 因为 pipe 在正则表达式中具有特殊含义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.您需要使用该组来获取正则表达式中括号内的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用Java正则表达式获取日期之间的内容 - How can i get content between dates using java regular expressions 正则表达式可在管道之间分割(括号中除外) - Regular expression to split between pipes except in brackets ANTLR4 如何创建允许除两个选定字符之外的所有字符的正则表达式? - ANTLR4 How can I create a regular expression that allows all characters except two selected ones? 如何使用正则表达式只获取`(`和`)`之间的字符? - How get only characters between `(` and `)` using regular expression? 如何使用正则表达式获取目录中不包含子目录的所有文件? - How to get all files in a directory with exclusion of subdirectories using regular expression? 如何使用 Java 正则表达式替换 URL 中的所有特殊字符? - How can I replace all special characters in a URL, using a Java regular expression? 如何通过匹配正则表达式提取所有子字符串? - How can I extract all substring by matching a regular expression? 如何找到replace_all的正则表达式? - How can I find this regular expression for replace_all? 如何找到android中正则表达式的所有匹配项 - How can I find all matches to a regular expression in android 我似乎无法让replaceAll工作(删除两个字符串之间的所有内容) - I can't seem to get replaceAll to work (remove all content between two strings)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM