在Java中拆分空格上的字符串,除非在引号之间(即将“hello world”视为一个标记)
如何基于空格拆分字符串,但将引用的子字符串作为一个单词 例如:在Java中拆分空格上的字符串,除非在引号之间(即将“hello world”视为一个标记),java,Java,如何基于空格拆分字符串,但将引用的子字符串作为一个单词 例如: Location "Welcome to india" Bangalore Channai "IT city" Mysore 它应存储在ArrayList中,如下所示: 以下是方法: String str = "Location \"Welcome to india\" Bangalore " + "Channai \"IT city\" Mysore"; List<String>
Location "Welcome to india" Bangalore Channai "IT city" Mysore
它应存储在ArrayList中,如下所示:
以下是方法:
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);
正则表达式只是说
[^]-以除
\S*-后跟零个或多个非空格字符
或
.+?-一个符号,后跟任何符号,直到另一个符号。
地点,欢迎来到印度,班加罗尔,香奈尔,IT城,迈索尔这是我在jsp表单中输入的一个字符串,提交后应该拆分,正如我在问题中提到的那样,双引号不应该在那里啊,将m.group1改为m.group1.replace\,@Tema,这个问题与。。。分组和应用程序特定。我强烈建议在处理字符串时使用String.trim,而不是使已经很复杂的regexp变得更复杂。遗憾的是,它在内部引号中失败:“exec-s something-e lala\lo lo\lululu-f$file”。它也不适用于单引号。如何像bash这样的命令行解释器解析这样的字符串?尽管dupe链接的问题比较老,但aioobe的这个答案是两者中最好的,因为它具有提取匹配项的高级正则表达式。
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]