假设我有一个像这样的字符串:
Hey man, my name is Jason and I like Pizza. #Pizza #Name #Cliche
我的问题是如何提取所有以#
开头的字符串并将它们放在另一个字符串中?
答案 0 :(得分:2)
尝试
Matcher matcher = Pattern.compile("(\\s|^)#(\\S*)").matcher(string);
while(matcher.find()){
System.out.println(matcher.group(2));
}
编辑:
如您还想要其他字符串,您可以尝试
Matcher matcher = Pattern.compile("(\\s|^)#(\\S*)|(\\S+)").matcher(string);
StringJoiner hashfull = new StringJoiner(" ");
StringJoiner hashless = new StringJoiner(" ");
while(matcher.find())
if(matcher.group(2) != null)
hashfull.add(matcher.group(2));
else if(matcher.group(3) != null)
hashless.add(matcher.group(3));
System.out.println(hashfull);
System.out.println(hashless);
答案 1 :(得分:1)
我发现这段代码对我来说非常好用,因为我还想要其余的字符串。感谢@Pshemo和@Mormod帮助我解决这个问题。这是代码:
String string = "Hello my name is Jason and I like pizza. #Me #Pizza";
String[] splitedString = string.split(" "); //splits string at spaces
StringBuilder newString = new StringBuilder();
StringBuilder newString2 = new StringBuilder();
for(int i = 0; i<splitedString.length; i++){
if(splitedString[i].startsWith("#")){
newString.append(splitedString[i]);
newString.append(" "); }
else{
newString2.append(splitedString[i]);
newString2.append(" ");
}
}
System.out.println(newString2);
System.out.println(newString);
答案 2 :(得分:0)
也许你会搜索这样的东西:
String string = "ab cd ef"
String[] splitedString = string.split(" "); //splits string at spaces
String newString = "";
for(int i = 0; i<splitedString; i++){
if(splitedString[i].startsWith("#")){
newString += splitedString[i];
}
}
mormod