gpt4 book ai didi

java - 在 Java 中的空格上拆分字符串,除非在引号之间(即将\"hello world\"视为一个标记)

转载 作者:IT老高 更新时间:2023-10-28 20:23:19 27 4
gpt4 key购买 nike

如何将String按空格分割,但把带引号的子串当作一个单词?

例子:

Location "Welcome  to india" Bangalore Channai "IT city"  Mysore

它应该存储在 ArrayList 作为

Location
Welcome to india
Bangalore
Channai
IT city
Mysore

最佳答案

方法如下:

String str = "Location \"Welcome  to india\" Bangalore " +
"Channai \"IT city\" Mysore";

List<String> list = new ArrayList<String>();
Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(str);
while (m.find())
list.add(m.group(1)); // Add .replace("\"", "") to remove surrounding quotes.


System.out.println(list);

输出:

[Location, "Welcome  to india", Bangalore, Channai, "IT city", Mysore]

正则表达式只是说

  • [^"]     - 以 "
  • 以外的内容开头的标记
  • \S*       - 后跟零个或多个非空格字符
  • ...或...
  • ".+?"   - 一个 "-symbol 后跟任何内容,直到另一个 "

关于java - 在 Java 中的空格上拆分字符串,除非在引号之间(即将\"hello world\"视为一个标记),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7804335/

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