在 Java 中的空格上拆分字符串,除非在引号之间(即将 “hello world" 视为一个标记) [英] Split string on spaces in Java, except if between quotes (i.e. treat "hello world" as one token)

查看:26
本文介绍了在 Java 中的空格上拆分字符串,除非在引号之间(即将 “hello world" 视为一个标记)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据空格拆分String,但将引用的子字符串作为一个词?

How do I split a String based on space but take quoted substrings as one word?

示例:

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*     - 后跟零个或多个非空格字符
  • ...或...
  • ".+?"   -一个 "-符号后跟任何东西,直到另一个 ".莉>
  • [^"]     - token starting with something other than "
  • S*       - followed by zero or more non-space characters
  • ...or...
  • ".+?"   - a "-symbol followed by whatever, until another ".

这篇关于在 Java 中的空格上拆分字符串,除非在引号之间(即将 “hello world" 视为一个标记)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆