java 如何在Java中找到字符串模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12636102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:39:16  来源:igfitidea点击:

How to find string pattern in Java

javaregexstring

提问by user1705636

Here is a string like this in Java.

这是 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.

我想搜索位于$[*]$模式中的单词。上述字符串的结果是A, B

回答by Nishant

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

回答by dteoh

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

使用正则表达式。在 Java 中,您可以使用Pattern 类

回答by Philipp

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

您可以为此使用正则表达式。看看类PatternMatcher

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

在这种情况下您将使用的正则表达式是:

$\[.*?\]$

Alternatively, you could work with String.indexOfand String.substr.

或者,您可以使用String.indexOfString.substr