Java分裂正在吃我的角色 [英] Java split is eating my characters

查看:98
本文介绍了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".

从我得到的我的正则表达式匹配$和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]"

正则表达式基本上是

(?<!\\)\$

它使用负向lookbehind断言前面没有 \

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

  • regular-expressions.info/Lookarounds

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

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]"

使用lookbehind / lookahead combo:

Using a lookbehind/lookahead combo:

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



相关问题



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