java 空格转义字符,在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 '\'

Eg:-

He is a "man of his" words\ always

must be split as

He

is

a

"man of his"

words\ always

I understand

List matchList = new ArrayList();

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

Matcher regexMatcher = regex.matcher(StringToBeMatched);

while (regexMatcher.find()) {

matchList.add(regexMatcher.group());

}

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+)

In Java:

Pattern regex = Pattern.compile

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

Explanation:

This regex works on alternation:

First match ([\"']).*?\\2 to match any quoted (double or single) strings.

Then match (?:[^\\ ]+\\\s+)+[^\\ ]+ to match any string with escaped spaces.

Finally Use \S+ to match any word with no spaces.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值