Home > Mobile >  Rails - regex: Get content between parenthesis(and without them) from string and get content after s
Rails - regex: Get content between parenthesis(and without them) from string and get content after s

Time:08-01

So I'm currently stuck with regex to get values properly. Let say we have an string like [VA03] SOME_ERROR_CODE

What I wish to get VA03 and SOME_ERROR_CODE in separate way using regex.

Currently I managed to get [VA03] (with parenthesis) via: [/\[.*?\]/] regex.

So my questions would be:

  • How to get VA03 without array parentheses?
  • How to get second pard of string which comes after space, e.g: SOME_ERROR_CODE

CodePudding user response:

If you want either the part between the square brackets, or non whitespace chars without square brackets:

\[\K[^]\[]*(?=])|[^]\[\s] 

Explanation

  • \[ Match [
  • \K Forget what is matched so far
  • [^]\[]* Optionally match any char except [ ]
  • (?=]) Assert ] directly to the right
  • | Or
  • [^]\[\s] Match 1 chars other than [ ] or a whitespace char

Rubular regex demo

If both values are in order, then you can use 2 capture groups:

\[([^]\[]*)]\s (\S )

Explanation

  • \[ Match [
  • ([^]\[]*) Capture group 1, match any char except [ ]
  • ] Match ]
  • \s Match 1 whitespace chars
  • (\S ) Capture group 2, match 1 non whitespace chars

Rubular regex demo

  • Related