SuS
SuS

Reputation: 71

regex to extract numbers from string

I have multiple strings and I want to extract only matching numbers .

Sample strings :

abc_efghi_92458_ijk_mno_uvw_test_v2_ghi003
AB_CD_E01_436873_MY_NAME_TESTING_O_001
testing-check-100001-23244-sln-001

I am expecting output as :

92458
436873
23244

I tried with +([^_]+) and +([\d{5,6}]+)

No luck Thanks

Upvotes: 0

Views: 2612

Answers (3)

symlink
symlink

Reputation: 12208

This will give you any contiguous sequence of numbers:

/[.*!\d](\d+)[.*!\d]/g

let arr = [
    "abc_efghi_92458_ijk_mno_uvw_test_v2_ghi003",
    "AB_CD_E01_436873_MY_NAME_TESTING_O_001",
    "testing-check-100001-23244-sln-001"
]

let re = /[.*!\d](\d+)[.*!\d]/g

let res = arr.map(str => str.match(re))

console.log(res)

Upvotes: 0

tauitdnmd
tauitdnmd

Reputation: 368

You can just simply iterable throw each string from the list. Then apply this regex: .*([-_])(\d+)\1 and get the group 2 if it matches. Then add the output to the result.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163642

For your example data you might use a capturing group and a backreference.

The value is in group 2

.*([-_])(\d+)\1

Regex demo

Upvotes: 1

Related Questions