Home > Blockchain >  How to replace (n) occurrences of a character with (n-1) occurrences of the same character in JavaSc
How to replace (n) occurrences of a character with (n-1) occurrences of the same character in JavaSc

Time:10-07

My data is

Hello ***** World

I need

Hello **** World

So basically 5 occurrences of star replaced with 4 occurrences of star. How can I do that In regex javascript.

NOTE: The number of star is dynamic.

I tried this but not sure how to replace the capturing group:

console.log("Hello ***** World".replace(/[a-zA-Z](.*)/gm,"$1||$3"));

UPDATE:

Wiktor's solution works like a charm. But not sure how to translate this to my actual problem I am facing in my regex. So I thought, it will be worth to post my actual problem.

My Data is this:

1.  HelloWorld

I need this

1.  HelloWorld

I need to reduce number of extra lines to n-1 between

[Numeric].[Space][Any text]

and

•[Three Spaces][AnyText]

and vice vera

•[Three Spaces][AnyText]

and 

[Numeric].[Space][Any text]

Note: Sorry for poor explanation. I am noob in regex.

CodePudding user response:

You can capture one or more asterisks and then match without capturing another (last in the sequence) asterisk, and replace with the backreference to the group value:

console.log("Hello ***** World".replace(/(\* )\*/g, "$1"));

See the regex demo.

There are other similar solutions here:

console.log("Hello ***** World".replace(/(\*)\*(?!\*)/g, '$1'));
console.log("Hello ***** World".replace(/(?<=\*)\*(?!\*)/g, ''));

See this regex demo #2 and regex demo #3.

In (\*)\*(?!\*), the first * is captured into Group 1, then an asterisk that has no other asterisk to the right of it is matched, and the $1 replacement does the job as in the first solution.

The (?<=\*)\*(?!\*) regex simply matches any asterisk that has an asterisk immediately on the left and no asterisk immediately on the right (that is why the replacement pattern is empty).

Applying this to a decreasing the amount of line breaks between two strings problem can look like

text = text.replace(/(\d \.\s.*(?:\r\n?|\n) )(?:\r\n?|\n)(?=•\s{3})/g, '$1').replace(/(•\s{3}.*(?:\r\n?|\n) )(?:\r\n?|\n)(?=\d \.\s)/g, '$1')

See this demo and another, "vice versa", demo.

Here, (?:\r\n?|\n) replaced the \* pattern and matches CRLF, LF or CR line endings. \s{3} matches any three whitespaces chars. \d \.\s matches one or more digits, . and a whitespace, and .* matches any zero or more chars other than line break chars, as many as possible (the rest of a line pattern). Lookaheads, (?=...), are used to make sure consecutive matches are matched.

  • Related