简体   繁体   English

正则表达式替换组

[英]Regular Expression to replace a group

I want to replace the space before the digits with some characters but i couldn't do that with the following regex: 我想用一些字符替换数字前的空格,但是我无法使用以下正则表达式来替换它:

    String parentString = " 1.skdhhfsdl 2. hkjkj 3.234hbn,m";
    String myregex = "/(\\s)[1-9]+./";
    String output = parentString.replaceAll(myregex, "$1ppp");
    System.out.println(output);

Please help me solve the regex. 请帮助我解决正则表达式。

UPDATE UPDATE

After implementing the suggestion by @CertainPerformant and @Wiktor my code looks like, 在实现@CertainPerformant和@Wiktor的建议之后,我的代码如下所示:

String myregex = "(\\s)[1-9]+.";
String output = parentString.replaceAll(myregex, "\n");

I want the output to be like 我希望输出像

1.skdhhfsdl
2. hkjkj
3.234hbn,m

But, i am currently getting 但是,我目前正在

1.skdhhfsdl
 hkjkj
234hbn,m

How about: 怎么样:

String myregex = "\\s([1-9]+\\.)";
String output = parentString.replaceAll(myregex, "\n$1");

You should use the regex 您应该使用正则表达式

\s+([1-9]+\.)

Notice that I captured the number part instead. 请注意,我改为捕获了数字部分。 When you are replacing, you usually capture the part you want to keep. 更换时,通常会捕获要保留的零件。 Also note that I removed the leading and trailing slashes as those are not needed in Java. 还要注意,我删除了前斜杠和后斜杠,因为Java中不需要这些斜杠。 The . . should also be escaped, like I did here. 也应该像我在这里一样逃脱。

The replacement is \\n$1 , meaning "new line, then group 1". 替换为\\n$1 ,表示“换行,然后是组1”。

String parentString = " 1.skdhhfsdl 2. hkjkj 3.234hbn,m";
String myregex = "\\s+([1-9]+\\.)";
String output = parentString.replaceAll(myregex, "\n$1");
System.out.println(output);

In order to get the expected output, you can use this regex. 为了获得预期的输出,可以使用此正则表达式。

public static void main(String[] args) throws Exception {
    String parentString = " 1.skdhhfsdl 2. hkjkj 3.234hbn,m";
    String myregex = "\\s+(?=[1-9]+\\.)";
    String output = parentString.trim().replaceAll(myregex, "\n");
    System.out.println(output);
}

This only matches one or more space that are followed by a number and dot and only replaces the space (because of lookahead) with a new line. 这仅匹配一个或多个空格,后跟数字和点,并且仅用换行符替换该空格(由于超前)。 parentString.trim() ensures that you don't get a newline before your first line. parentString.trim()确保在第一行之前不会出现换行符。

Output: 输出:

1.skdhhfsdl
2. hkjkj
3.234hbn,m

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM