sam
sam

Reputation: 2004

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

After implementing the suggestion by @CertainPerformant and @Wiktor my code looks like,

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

Upvotes: 0

Views: 72

Answers (3)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

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.

Output:

1.skdhhfsdl
2. hkjkj
3.234hbn,m

Upvotes: 1

Sweeper
Sweeper

Reputation: 270860

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. The . should also be escaped, like I did here.

The replacement is \n$1, meaning "new line, then group 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);

Upvotes: 1

Maurice Perry
Maurice Perry

Reputation: 9651

How about:

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

Upvotes: 1

Related Questions