pits
pits

Reputation: 23

Regex - to extract text before the last a hyphen/dash

Example data                         expected output   

sds-rwewr-dddd-cash0-bbb              cash0
rrse-cash1-nonre                      cash1
loan-snk-cash2-ssdd                   cash2
garb-cash3-dfgfd                      cash3
loan-unwan-cash4-something            cash4

The common pattern is here, need to extract a few chars before the last hyphen of given string.

var regex1= /.*(?=(?:-[^-]*){1}$)/g ;       //output will be "ds-rwewr-dddd-cash0" from "sds-rwewr-dddd-cash0-bbb  "
var regex2 = /\w[^-]*$/g ;       //output will be "cash0" from "ds-rwewr-dddd-cash0"
var res =regex2.exec(regex1.exec(sds-rwewr-dddd-cash0-bbb)) //output will cash0

Although above nested regex is working as expected but may not be optimize one. So any help will be appreciated for optimized regex

Upvotes: 1

Views: 1500

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You can use

/\w+(?=-[^-]*$)/

If the part before the last hyphen can contain chars other than word chars, keep using \w[^-]*: /\w[^-]*(?=-[^-]*$)/. If you do not need to check the first char of your match, simply use /[^-]+(?=-[^-]*$)/.

See the regex demo.

Details:

  • \w+ - one or more word chars
  • (?=-[^-]*$) - that must be followed with - and then zero or more chars other than - till the end of string.

JavaScript demo

const texts = ['sds-rwewr-dddd-cash0-bbb','rrse-cash1-nonre','loan-snk-cash2-ssdd','garb-cash3-dfgfd','loan-unwan-cash4-something'];
const regex = /\w+(?=-[^-]*$)/;
for (var text of texts) {
  console.log(text, '=>', text.match(regex)?.[0]);
}

Upvotes: 1

Related Questions