这里我有下面的代码。这个想法是使用像“R#GUPW*UIOPW#WERTY*RT#LLOPPPPER*CVW”这样的短语来返回这样的模式
“#GUPW*”
“#WERTY*”
“#LLOPPPPER*”
返回短语中以 # 开头、以 * 结尾的所有子字符串。所以这个短语中有 3 个。
import java.io.*;
public class Pattern {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String phrase = "R#GUPW*UIOPW#WERTY*RT#LLOPPPPER*CVW";
String found ="";
for (int y = 0; y<phrase.length(); y++)
{
found = found + phrase.substring(phrase.indexOf("#"), phrase.indexOf("*"));
}
System.out.println(found);
}
}
但是我的代码返回
“#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW #GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW#GUPW"
如何从我的短语中返回这些以 # 开头并以 * 结尾的子字符串。
“#GUPW*”
“#WERTY*”
“#LLOPPPPER*”
最佳答案
解决方案是定义一个Pattern
,然后在Matcher
中使用它。
List<String> allMatches = new ArrayList<String>();
Pattern p = Pattern.compile("#[^*]+\\*");
Matcher m = p.matcher(yourString);
while (m.find()) {
allMatches.add(m.group());
}
然后,所有匹配项都会出现在列表
中。
演示:
String s = "R#GUPW*UIOPW#WERTY*RT#LLOPPPPER*CVW";
List<String> allMatches = new ArrayList<String>();
Pattern p = Pattern.compile("#[^*]+\\*");
Matcher m = p.matcher(s);
while (m.find()) {
allMatches.add(m.group());
}
for (String str : allMatches) {
System.out.println(str);
}
>>#GUPW*
>>#WERTY*
>>#LLOPPPPER*
关于java - 返回字符串中找到的相同子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41675585/