正则表达式上的String.split()* not *? [英] String.split() *not* on regular expression?

查看:107
本文介绍了正则表达式上的String.split()* not *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 String.split()适用于正则表达式,因此该片段:

Since String.split() works with regular expressions, this snippet:

String s = "str?str?argh";
s.split("r?");

...收益率: [,s,t ,,?,s ,t,,?,a,g,h]

在<$ c $上拆分此字符串的最优雅方法是什么c> r?序列,以便它产生 [st,st,argh]

编辑:我知道我可以逃避有问题的。问题是我不知道分隔符,我不想通过写一个 escapeGenericRegex()函数来解决这个问题。

EDIT: I know that I can escape the problematic ?. The trouble is I don't know the delimiter offhand and I don't feel like working this around by writing an escapeGenericRegex() function.

推荐答案

仅使用Java SE API的一般解决方案是:

A general solution using just Java SE APIs is:

String separator = ...
s.split(Pattern.quote(separator));

quote 方法返回一个正则表达式将参数字符串作为文字匹配。

The quote method returns a regex that will match the argument string as a literal.

这篇关于正则表达式上的String.split()* not *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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