Home > Net >  Regex to truncate last 4 characters and make sure it doesn't contain specific words
Regex to truncate last 4 characters and make sure it doesn't contain specific words

Time:02-10

I get strings such as "BumpCardV2Resource.getInstance.Time" or "BumpCardWebResource.getInstance.Time" or "BumpCardResource.getInstance.Time". I need a regex expression to obtain only "BumpCardResource.getInstance"

Currently, I'm using a negative look ahead to make sure the string does not contain V2 or Web but not sure how to truncate the last 5 characters (.Time) along with that.

Regex I'm using: /^(?!.*V2|.*WebResource).*$/

PS - The resource and the API endpoint keeps changing. It need not be necessarily only BumpCard or getInstance

CodePudding user response:

You can use a regex where you match the whole string and capture any text from the start of the string till .Time at the end of it:

/^(?!.*V2|.*WebResource)(.*)\.Time$/

See the regex demo. Details:

  • ^ - start of string
  • (?!.*V2|.*WebResource) - no V2 or WebResource allowed anywhere in the string
  • (.*) - Capturing group 1: any zero or more chars other than line break chars as many as possible
  • \.Time - .Time string
  • $ - end of string.
  • Related