-3

I am new to regular expression and I am trying to form a regular expression for below scenarios having combination of letters and decimal number upto 2 precision:

GBP 23.44   -> Valid

23.44       -> Valid

23          -> Valid

23 GBP      -> Valid

234.44 GBP  -> Valid

234.44      -> Valid

23.334 GBP  -> Invalid

234.443 GBP -> Invalid

234& GBP    -> Invalid  

Moreover no other characters should be allowed other than A-Z and a-z and Number with 2 precisions.

My attempt:

I tried ^[Aa-Zz][0-9]+(\\.[0-9]{1,2})?$, but its not working as per the expression numbers always needed to be followed after characters like 234.44 GBP is failing to match.

I am not able to form exact expression which satisfy all the scenarios. Please help.

vrintle
  • 5,501
  • 2
  • 16
  • 46
riya ahuja
  • 260
  • 6
  • 18
  • Can you provide your failed attempt? – achAmháin Oct 25 '18 at 11:08
  • I think this or similar is answered in this [case](https://stackoverflow.com/questions/308122/simple-regular-expression-for-a-decimal-with-a-precision-of-2) – Tihomir Oct 25 '18 at 11:09
  • @achAmháin I tried ^[Aa-Zz][0-9]+(\\.[0-9]{1,2})?$ but its not working ans as per expression numbers always need to be followed after characters so 234.44 GBP this is failing – riya ahuja Oct 25 '18 at 11:22

1 Answers1

2

So looks like only matches to be rejected are where number has 3 decimal places and GBP doesn't matter as long as it is accompanied by a number. You may use this regex,

^(?!\d+\.\d{3})[a-zA-Z0-9. ]*$

Demo here, https://regex101.com/r/1HlV8z/2

Let me know if it works fine for you or you have any other custom needs.

Edit1: Updated my regex to meet your valid character needs. Valid characters allowed shall be upper/lower alphabets, numbers, dot and space.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36