Home > Net >  Distinguishing numbers with REGEXREPLACE
Distinguishing numbers with REGEXREPLACE

Time:02-14

I am aware that regex does not work with numeric values, yet, how can we have a regex pattern to differentiate between numbers in a Google sheets formula?

For example: >=13 and <13

A B
desired result
5 5♥
2 2♥
13 13♦♦♦
12 12♥
30 30♦♦♦
17 17♦♦♦
0 0♥
-4 -4♥
-12 -12♥
22 22♦♦♦
-55 -55♥
31 31♦♦♦
-13 -13♥
-31 -31♥

enter image description here

I can solve this in alternative ways like:

=INDEX(REGEXREPLACE(REGEXREPLACE(REGEXREPLACE("" & A2:A16,
 "\b(^" & JOIN("$|^", SEQUENCE(13, 1, )) & "$)\b", "$1♥"),
 "(^-\d )", "$1♥"),
 "(\d $)", "$1♦♦♦"))

...but I feel there could be some more "regexy" solution.

Rules of combat:

  • regex pattern
  • no IF-statements
  • >=13 add ♦♦♦
  • <13 add ♥
  • no IFERROR pivots
  • no non-regex solutions

CodePudding user response:

You could first add the diamonds and then replace those by a heart when the number is less than 13:

=REGEXREPLACE(A1 & "♦♦♦"; "^(-\d |1[0-2]|\d)♦♦♦$"; "$1♥")

The regular expression looks for three patterns:

  • -\d : any negative number
  • 1[0-2]: 10, 11 or 12
  • \d: 0,1,2,..., or 9.

CodePudding user response:

Try:

=REGEXREPLACE(REGEXREPLACE(TO_TEXT(A1), "^(-\d |[0-9]|1[0-2])$", "$1♥"), "^([^♥] )$", "$1♦♦♦")

enter image description here

  • Related