Home > database >  Perl regex: discriminate mandatory and optional characters
Perl regex: discriminate mandatory and optional characters

Time:06-17

The question is about PERL regular expressions.

I need to match a string that

  • starts with < and ends with >
  • must contain number [0-9]
  • can optionally contain \s (i.e. space) and ,
  • any number of characters
  • order is random

This pattern does not discriminate between mandatory and optional characters:

/<[0-9,\s] >/

and will match:

<9>
<9,10>
<9, 10>

which is what I want, but also these two that I dont want:

< >
<,>

So, how to set a PERL regex that will find a match that will always contain 0-9 and can optionally contain \s, ?

CodePudding user response:

how to set a PERL regex that will find a match that will always contain 0-9 and can optionally contain \s,:

Verbatim for this requirement, you can use this regex:

/<[\d,\h]*\d[\d,\h]*>/

Which stands for:

  • <: Match a <
  • [\d,\h]*: Match 0 or more digits or whitespace or comma
  • \d: Match a digit
  • [\d,\h]*: Match 0 or more digits or whitespace or comma
  • >: Match a >

RegEx Demo

CodePudding user response:

You can use

<\d (?:,\s*\d )*>

See the regex demo. Details:

  • < - a < char
  • \d - one or more digits
  • (?:,\s*\d )* - zero or more occurrences of a ,, zero or more whitespaces and then one or more digits
  • > - a > char.
  • Related