RegEx needed to match number to exactly two decimal places

后端 未结 5 1384
醉梦人生
醉梦人生 2020-12-06 09:48

I need some regex that will match only numbers that are decimal to two places. For example:

  • 123 = No match
  • 12.123 = No match
  • 12.34 = Match
5条回答
  •  感情败类
    2020-12-06 10:37

    It depends a bit on what shouldn't match and what should and in what context

    for example should the text you test against only hold the number? in that case you could do this:

    /^[0-9]+\.[0-9]{2}$/
    

    but that will test the entire string and thus fail if the match should be done as part of a greater whole

    if it needs to be inside a longer styring you could do

    /[0-9]+\.[0-9]{2}[^0-9]/
    

    but that will fail if the string is is only the number (since it will require a none-digit to follow the number)

    if you need to be able to cover both cases you could use the following:

    /^[0-9]+\.[0-9]{2}$|[0-9]+\.[0-9]{2}[^0-9]/
    

提交回复
热议问题