gpt4 book ai didi

java - 如何用引号、站点运算符和非引号拆分字符串?

转载 作者:行者123 更新时间:2023-12-01 19:36:11 25 4
gpt4 key购买 nike

我收到这样的用户请求

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com