本文介绍了Java 分裂正在吞噬我的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串 String str = "la$le\$li$lo".

I have a string like this String str = "la$le\$li$lo".

我想拆分它以获得以下输出"la","le\$li","lo".$ 是 $ 转义的,所以它应该留在输出中.

I want to split it to get the following output "la","le\$li","lo". The $ is a $ escaped so it should be left in the output.

但是当我做 str.split("[^\\]\$") y get "l","le\$l","lo".

But when I do str.split("[^\\]\$") y get "l","le\$l","lo".

从我得到的正则表达式匹配 a$ 和 i$ 然后删除.知道如何恢复我的角色吗?

From what I get my regex is matching a$ and i$ and removing then. Any idea of how to get my characters back?

谢谢

推荐答案

使用零宽度匹配断言:

    String str = "la$le\$li$lo";
    System.out.println(java.util.Arrays.toString(
        str.split("(?<!\\)\$")
    )); // prints "[la, le$li, lo]"

正则表达式本质上是

(?<!\)$

它使用否定后视来断言没有前面的 .

It uses negative lookbehind to assert that there is not a preceding .

简单的句子拆分,保留标点符号:

Simple sentence splitting, keeping punctuation marks:

    String str = "Really?Wow!This.Is.Awesome!";
    System.out.println(java.util.Arrays.toString(
        str.split("(?<=[.!?])")
    )); // prints "[Really?, Wow!, This., Is., Awesome!]"

使用G

    String str = "012345678901234567890";
    System.out.println(java.util.Arrays.toString(
        str.split("(?<=\G.{4})")
    )); // prints "[0123, 4567, 8901, 2345, 6789, 0]"

使用后视/前瞻组合:

    String str = "HelloThereHowAreYou";
    System.out.println(java.util.Arrays.toString(
        str.split("(?<=[a-z])(?=[A-Z])")
    )); // prints "[Hello, There, How, Are, You]"

相关问题

10-10 21:30