sda
sda

Reputation: 143

Perl regex: discriminate mandatory and optional characters

The question is about PERL regular expressions.

I need to match a string that

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, ?

Upvotes: 1

Views: 86

Answers (2)

anubhava
anubhava

Reputation: 784998

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

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

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.

Upvotes: 0

Related Questions