Pawan.Java
Pawan.Java

Reputation: 759

Regex to extract the username from a string

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?

Upvotes: 1

Views: 364

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

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

Upvotes: 1

Radu Diță
Radu Diță

Reputation: 14211

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,"")

Upvotes: 0

Related Questions