我有一个像这样的字符串..
I am a !!!guy!!! but I like !!!cats!!! better than dogs.
我需要在感叹号字符串(!!!)中的字符串,字符串或数组的集合。
我可以用String的substring和indexOf做一个肮脏的方式,但是如果你可以建议一个更好的方法来使用正则表达式或者只是更清晰的代码,那将非常感激。
感谢。
答案 0 :(得分:2)
您可以使用这样的简单正则表达式:
!!!(.*?)!!!
然后抓住捕获组内容
<强> Working demo 强>
匹配信息
MATCH 1
1. [10-13] `guy`
MATCH 2
1. [31-35] `cats`
你可以使用类似这样的java代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "I am a !!!guy!!! but I like !!!cats!!! better than dogs.";
String pattern = "!!!(.*?)!!!";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
while (m.find( )) {
//--> If you want a array do the logic you want with m.group(1)
System.out.println("Found value: " + m.group(1) );
}
}
}