Home > other >  How to backreference group when using or in regex?
How to backreference group when using or in regex?

Time:12-01

I am using TypeScript and I want to remove all the comments from the code using regex. Here's my sample code:

// this is awesome code
const a =1

// this is nice
const b = 2 // oh great


  // with some indentation
const x = 99

I want to preserve the new lines as it is and want to remove all the lines so final output should look like the below:

const a =1

const b = 2


const x = 99

To achieve above I have to write regex: ^( *\/\/.*)\n|( *\/\/.*)

The question is how can I backreference the first group after or | condition? I can't do ^( *\/\/.*)\n|(\1).

P.S. I am using regex101.com for testing

Thanks.

CodePudding user response:

You can search using this regex:

^[ \t]*\/\/.*\r?\n|[ \t]*\/\/.*

And replace with empty string.

RegEx Demo

RegEx Details:

  • ^: Start
  • [ \t]*: Match 0 or more horizontal whitespaces
  • \/\/: Match //
  • .*: Match everything till end of line
  • \r?\n: Match optional carriage return followed by line feed character
  • |: OR
  • [ \t]*: Match 0 or more horizontal whitespaces
  • \/\/: Match //
  • .*: Match everything till end of line
  • Related