在java中基于空格分割一个字符串,用双引号和单引号转义那些空格以及前面带有\的空格 [英] Split a string in java based on white spaces escaping those spaces in double quotes and single quotes and that which are preceded by \

查看:336
本文介绍了在java中基于空格分割一个字符串,用双引号和单引号转义那些空格以及前面带有\的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式完全不熟悉。我正在尝试将一个表达式放在一起,该表达式将使用未被单引号或双引号括起的所有空格拆分示例字符串,并且前面没有'\'

I am totally new to regular expressions. I'm trying to put together an expression that will split the example string using all spaces that are not surrounded by single or double quotes and are not preceded by a '\'

例如: -

He is a "man of his" words\ always

必须拆分为

He
is 
a 
"man of his"
words\ always

我理解

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(StringToBeMatched);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group());
}

l使用未被single或double包围的所有空格拆分示例字符串引号

l split the example string using all spaces that are not surrounded by single or double quotes

如果前面有一个\ ??

How do I incorporate the third condition of ignoring the white-space if it is preceded by a \ ??

推荐答案

你可以使用这个正则表达式:

You can use this regex:

((["']).*?\2|(?:[^\\ ]+\\\s+)+[^\\ ]+|\S+)



RegEx演示



在Java中:

Pattern regex = Pattern.compile
   ( "(([\"']).*?\2|(?:[^\\\\ ]+\\\\\s+)+[^\\\\ ]+|\\S+)" );

说明:

这个正则表达式适用于交替:

This regex works on alternation:


  1. 第一场比赛([\'])。*? \\\\ 匹配任何引用的(双重或单个)字符串。

  2. 然后匹配(?:[^ \\\ \\] + \\\ + + + + [^ \\] + 匹配任何带有转义空格的字符串。

  3. 最后使用 \S + 匹配任何没有空格的单词。

  1. First match ([\"']).*?\\2 to match any quoted (double or single) strings.
  2. Then match (?:[^\\ ]+\\\s+)+[^\\ ]+ to match any string with escaped spaces.
  3. Finally Use \S+ to match any word with no spaces.

这篇关于在java中基于空格分割一个字符串,用双引号和单引号转义那些空格以及前面带有\的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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