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

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

问题描述

如何根据空格拆分字符串,但是将带引号的子字符串作为一个单词?

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 * &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; - 后跟零个或多个非空格字符

  • ...或...

  • 。+?     - -symbol后跟任何内容,直到另一个

  • [^"]     - 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天全站免登陆