简体   繁体   中英

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 {AZ} only. Can i have a regex that removes the X parts with the underscore as well?

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

In the replacement use an empty string.

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

Regex demo

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(/^([AZ]+_?){0,2}/g,"")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM