Home > Software engineering >  Regex to extract the username from a string
Regex to extract the username from a string

Time:06-20

I have a string name that can include the following possiblities and I wish to use a regex expression to remove that X part of the string with its corresponding underscore and obtain the filename only.

Possibilities of string name:

  1. XXX_XXX_filename
  2. XXX_filename

kindly note that X is an uppercase and consists of alphabets {A-Z} only. Can i have a regex that removes the X parts with the underscore as well?

CodePudding user response:

You can repeat 1 or 2 times matching 1 or more uppercase chars [A-Z] followed by an underscore.

In the replacement use an empty string.

(?:[A-Z] _){1,2}

Regex demo

CodePudding user response:

You can try this:

"XXX_XXX_filename".replace(/^[A-Z_]*/g,"")

If you know the number of total characters you can restrict the regexp a bit more:

"XXX_XXX_filename".replace(/^[A-Z_]{3,7}/g,"")

If you also know the total number of groups for upper case you could use this alos:

"XXX_XXX_Filename".replace(/^([A-Z] _?){0,2}/g,"")

  • Related