Skip to content
Advertisement

Extract text between last slash and last dot using regex

I have string like this in javascript

at LoggerService.log (/Users/apps/api/webpack:/pcs-goc-api/pcs-libs/logger/src/logger.service.ts:107:29)

I want to extract logger.service from it. the formula is between last / to last .

I can extract from last / using /([^/]+$)/g but don’t know how to limit the finding to last .

Note: these are other examples:

at LoggerService.log (/Users/apps/api/webpack:/pcs-goc-api/pcs-libs/logger/src/logger.ts:107:29) expected: logger

at LoggerService.log (/Users/apps/api/webpack:/pcs-goc-api/pcs-libs/logger/src/logger.js:107:29) expected: logger

at LoggerService.log (/Users/apps/api/webpack:/pcs-goc-api/pcs-libs/logger/src/api.logger.service.ts:107:29) expected: api.logger.service

Advertisement

Answer

You can use

/.*/(.*)./

Details:

  • .* – any zero or more chars other than line break chars as many as possible
  • / – a / char
  • (.*) – Group 1: any zero or more chars other than line break chars as many as possible
  • . – a . char.

See the JavaScript demo:

const text = "at LoggerService.log (/Users/apps/api/webpack:/pcs-goc-api/pcs-libs/logger/src/api.logger.service.ts:107:29)";
const match = text.match(/.*/(.*)./)
if (match) {
    console.log(match[1]);
}
Advertisement