拆分多个分隔符不起作用(Split with multiple delimiters not working)

由于某种原因,我的多分隔符拆分不起作用。 希望它只是一个语法错误。

这有效,但我想在找到结束日期时拆分

String dateList[] = test.split("(?="+StartDate+")");

但事实并非如此。 我错过了什么吗?

String dateList[] = text.split("[(?="+StartDate+")(?="+EndDate+")]");

For some reason my multi delimiter split is not working. Hope it just a syntax error.

This works, but I want to also split if it finds end date

String dateList[] = test.split("(?="+StartDate+")");

But this does not. Am I missing something?

String dateList[] = text.split("[(?="+StartDate+")(?="+EndDate+")]");

最满意答案

您不能在自定义字符类中使用“lookarounds” - 它们只会被解释为类的字符(如果检测到格式错误的范围,甚至可能无法正确编译模式,例如使用悬空字符)。

使用| 运算符在StartDate和EndDate之间交替。

就像是:

String dateList[] = text.split("(?="+StartDate+"|"+EndDate+")");

笔记

您还可能希望在开始日期和结束日期值上调用Pattern.quote ,以防它们包含保留字符。 Java变量命名约定是camelBack ,而不是CamelCase

You cannot use "lookarounds" in a custom character class - they'd be just interpreted as characters of the class (and may not even compile the pattern properly if a malformed range is detected, e.g. with dangling - characters).

Use the | operator to alternate between StartDate and EndDate.

Something like:

String dateList[] = text.split("(?="+StartDate+"|"+EndDate+")");

Notes

You also may want to invoke Pattern.quote on your start and end date values, in case they contain reserved characters. Java variable naming convention is camelBack, not CamelCase

更多推荐