How to get a 4-digit number from a given string using Regex?
Given the string something/word/statement-fm-4512-co-km458
, how can we use Regex to get the 4-digit number (4512) that is not always after fm-
or before -co
?
Given the string something/word/statement-fm-4512-co-km458
, how can we use Regex to get the 4-digit number (4512) that is not always after fm-
or before -co
?
The following Regex pattern can be used to extract the 4-digit number from the given string:
(?<=fm-)\d{4}|(?<=-)\d{4}(?=-co)
Explanation:
(?<=fm-)\d{4}
matches any 4-digit number that comes after fm-
using a positive lookbehind (?<=fm-)
.|
or operator is used to match either the first or second pattern.(?<=-)\d{4}(?=-co)
matches any 4-digit number that is preceded by a -
and followed by -co
using positive lookarounds (?<=-)
and (?=-co)
respectively.