Raphael Alejandro Raphael Alejandro - 5 months ago 10
Javascript Question

Regex to match numbers greater than 0, within parenthesis and if the second last character as string

I'm not really sure how to do the below in Regex, could you help me?

I'm developing an app that scrape a page, and as a result I get:

["(02335E)", "(02743M)", "(00899G)", "(02657J)",
"(03330B)", "(03359M)", "(Macquarie)", "(00002J)",
"(01994M)", "(00401E)", "(Australia)", "(02517K)",
"(01545C)", "(03245K)", "(00168J)", "(03258E)",
"(00172B)", "(02318F)", "(02778M)", "(03350J)",
"(00682B)", "(03265F)", "(from 354 rows)"]


How can I match in Javascript Regex only the numbers grater than zero inside these parenthesis when the string ends (before the parenthesis) with any character (like
E
,
M
,
G
,
J
,
B
,
F
, etc)?

So, for example, in the string,
(02335E)
, I would get
2335
, and in the string
(00682B)
, I would get
682
.

Thank you for your help.

Answer
"(02335E)".match(/^\(0*([1-9]\d*)[A-Za-z_]*\)$/)[1];

Explanation:

  • ^: Start of the string.
  • \(: A literal left paren.
  • 0*: Zero or more zeros.
  • ([1-9]\d*): Capture a 1-9, following by zero or more digits.
  • [A-Za-z_]*: Zero or more word characters (minus any digits).
  • \): A literal right paren.
  • $: The end of the string.