Sergey Tonkoshkurik Sergey Tonkoshkurik - 3 months ago 8
Javascript Question

Retrieve BSR and category from string with RegExp

When I parse Amazon products I get this such of string.

"#19 in Home Improvements (See top 100)"


I figured how to retrieve BSR number which is
/#\d*/

But have no idea how to retrieve Category which is going after
in
and end until brackets
(See top 100)
.

Answer

I suggest

#(\d+)\s+in\s+([^(]+?)\s*\(

See the regex demo

var re = /#(\d+)\s+in\s+([^(]+?)\s*\(/; 
var str = '#19 in Home Improvements (See top 100)';
var m = re.exec(str);
if (m) {
  console.log(m[1]);
  console.log(m[2]);
}

Pattern details:

  • # - a hash
  • (\d+) - Group 1 capturing 1 or more digits
  • \s+in\s+ - in enclosed with 1 or more whitespaces
  • ([^(]+?) - Group 2 capturing 1 or more chars other than ( as few as possible before th first...
  • \s*\( - 0+ whitespaces and a literal (.
Comments