在Java String.split()方法中使用转义字符处理分隔符 [英] Handling delimiter with escape characters in Java String.split() method

查看:590
本文介绍了在Java String.split()方法中使用转义字符处理分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索了我的查询,但没有得到完全符合我要求的答案。我的字符串如下:

I have searched the web for my query, but didn't get the answer which fits my requirement exactly. I have my string like below:

A|B|C|The Steading\|Keir Allan\|Braco|E

我的输出应如下所示:

A
B
C
The Steading|Keir Allan|Braco
E

我的要求是跳过分隔符(如果前面有分隔符)逃脱序列。我在 String.split()中尝试使用负面lookbehinds:

My requirement is to skip the delimiter if it is preceded by the escape sequence. I have tried the following using negative lookbehinds in String.split():

(?<!\\)\|

但是,我的问题是分隔符将由最终用户动态定义,并且不必总是 | 。它可以是键盘上的任何字符(没有限制)。因此,我怀疑上述正则表达式可能会因正则表达式中不允许的某些特殊字符而失败。

But, my problem is the delimiter will be defined by the end user dynamically and it need not be always |. It can be any character on the keyboard (no restrictions). Hence, my doubt is that the above regex might fail for some of the special characters which are not allowed in regex.

我只是想知道这是否是完美的方式要做到这一点。

I just wanted to know if this is the perfect way to do it.

推荐答案

你可以使用 Pattern.quote()

You can use Pattern.quote():

String regex = "(?<!\\\\)" + Pattern.quote(delim);






使用您的示例:


Using your example:

String delim = "|";
String regex = "(?<!\\\\)" + Pattern.quote(delim);

for (String s : "A|B|C|The Steading\\|Keir Allan\\|Braco|E".split(regex))
    System.out.println(s);




A
B
C
The Steading\|Keir Allan\|Braco
E






您可以扩展它以使用自定义转义序列:


You can extend this to use a custom escape sequence as well:

String delim = "|";
String esc = "+";
String regex = "(?<!" + Pattern.quote(esc) + ")" + Pattern.quote(delim);

for (String s : "A|B|C|The Steading+|Keir Allan+|Braco|E".split(regex))
    System.out.println(s);




A
B
C
The Steading+|Keir Allan+|Braco
E

这篇关于在Java String.split()方法中使用转义字符处理分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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