Tuesday, February 27, 2018

Regular Expression to get a string between parentheses



This article is based on the regular expression which returns a string which is between parentheses. For example: I want to get the string which resides between the strings "(" and ")"

I expect five hundred dollars ($500).
would return
$500
So You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:

var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");

//matches[1] contains the value between the parentheses
console.log(matches[1]);
Breakdown:
  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses

Thursday, February 15, 2018

Hierarchical data in MySQL: parents and children in one query

The idea is, how to implement a hierarchical query in MySQL (using the ancestry chains version) for a single row, such that it picks up the parents (if any) and any children (if any).

We need to combine two queries here:
  1. Original hierarchical query that returns all descendants of a given id (a descendancy chain)
  2. A query that would return all ancestors of a given id (an ancestry chain)
An id can have only one parent, that's why we can employ a linked list technique to build an ancestry chain, like shown in this article:

Here's the query to to this (no functions required):


SELECT  CONCAT(REPEAT('    ', level  - 1), _id) AS treeitem, parent, level
FROM    (
        SELECT  @r AS _id,
                (
                SELECT  @r := parent
                FROM    t_hierarchy
                WHERE   id = _id
                ) AS parent,
                @l := @l + 1 AS level
        FROM    (
                SELECT  @r := 1218,
                        @l := 0,
                        @cl := 0
                ) vars,
                t_hierarchy h
        WHERE   @r <> 0
        ORDER BY
                level DESC
        ) qi

Click to see more details. Thanks to Quassnoi to made my day easy!!