作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我收到这样的用户请求
site:www.example.com \"hello world\" \"hi abc\" where are you
我想从这个字符串中提取并保存 url,然后将其从上面的字符串中删除,它应该看起来像这样 "hello world""hi abc"where are you
现在将剩余的字符串分成两个字符串数组
String str1 = {hello world, hi abc};
String str2 = {where, are, you};
我怎样才能在java中做到这一点?用户查询可以按任何顺序。各种示例:
"hi" excitement site:www.example.com \"hello world\" \"hi abc\" where are you "amazing"
OR
Hello World friends
OR
Greeting is an "act of communication" human beings "intentionally"
最佳答案
我认为这段代码可以帮助你:
static class ExtractResponse {
String newStr;
String site;
}
public static ExtractResponse extractSite(String origin) {
Pattern pattern = Pattern.compile("site:\\S* ");
Matcher matcher = pattern.matcher(origin);
ExtractResponse response = new ExtractResponse();
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
response.site = matcher.group().substring(5); // 5 is length of "site:"
matcher.appendReplacement(buffer, "");
}
matcher.appendTail(buffer);
response.newStr = buffer.toString();
return response;
}
它将返回包含新字符串的响应,不含 site:* 和站点的 url。例如,我使用了您的答案和评论中的案例:
public static void main(String[] args) {
String str1 = "site:www.example.com \"hello world\" \"hi abc\" where are you";
String str2 = "\"hello world\" \"hi abc\" site:www.example.com where are you";
ExtractResponse response1 = extractSite(str1);
System.out.println(response1.newStr);
System.out.println(response1.site);
ExtractResponse response2 = extractSite(str2);
System.out.println(response2.newStr);
System.out.println(response2.site);
}
输出:
"hello world" "hi abc" where are you
www.example.com
"hello world" "hi abc" where are you
www.example.com
关于java - 如何用引号、站点运算符和非引号拆分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59217053/
我是一名优秀的程序员,十分优秀!