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

标签 java string parsing

我收到这样的用户请求

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/

相关文章:

javascript - Json 到 javascript 字典

java - 我在哪里可以在 Spring 3.1 中指定 Jackson SerializationConfig.Feature 设置

JavaScript:拆分逗号分隔的字符串但忽略花括号

python - 使用ElementTree逐一解析目录下的所有xml文件

java - 访问没有对象的字符串类的方法

string - 如何将 Int 值转换为 String?

java - java中如何等待一项任务完成?

java - 用于多个标签的 JScrollPane

java - 谁能确认咖啡字节是否可以与 eclipse 氧气一起使用?

java - Java中Collection和Arraylist的区别?