我的输入字符串包含混合类型的行分隔符,包括“\r\n”、“\r”或“\n”。我想拆分字符串并保留行分隔符及其前面的子字符串。我关注了下面的两个帖子
How to split a string, but also keep the delimiters?
然后想出类似的东西:
String input = "1 dog \r\n 2 cat";
String[] output = input.split( "(?<=((\\r\\n)|\\r|\\n))")));
输出是 ["1 dog\r", "\n", "2 cat"]
,但是期望的输出是 ["1 dog\r\n", “2 只猫”]
。
如果我将输入更改为 String input = "1 dog\r 2 cat";
或 String input = "1 dog\n 2 cat";
,我的代码可以产生所需的输出。请指教。提前致谢。
最佳答案
你得到你的结果 ["1 dog\r", "\n", "2 cat"]
因为你的模式使用了一个交替匹配 (\r\n )
或 \r
或 \n
。
当在示例字符串中遇到\r\n
时,lookbehind断言在\r
之后将为真,并且会第一次拆分。
然后在 \n
之后 lookbehind 断言将为真,并将进行第二次拆分。
你可能会做的是在正后视中使用 \R
来断言左边的是 unicode newline sequence :
String input = "1 dog \r\n 2 cat";
String[] output = input.split("(?<=\\R)");
修复正则表达式的另一种方法是将其设为 atomic group :
(?<=(?>\\r\\n|\\r|\\n))
阅读 this post ,当 \r
在 lookbehind 中使用原子组匹配时,下面的 \n
也匹配。
关于Java 将字符串拆分为 '\r\n' 、 '\r' 或 '\n' 并与前面的子字符串保持一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55566172/