Home > Net >  Regex expression with decimals, one letter and a question mark
Regex expression with decimals, one letter and a question mark

Time:12-03

I'm trying to make a suvat calculator so one can input decimals, a letter (e.g., S) and a question mark if you do not have a value.

Tests that will be valid include "2.3", "S", "?" but not values like "2.5s", "??", etc (only one type, can't have decimals AND a letter in the same input box)

Is there a regex expression for this? So far I have only got the regex for the decimal number:

 ^[0-9]\\d*(\\.\\d )

I did also try a way simpler one but I would like a more developed expression for later on.

[0-9sS.?]

CodePudding user response:

You can use

@"^(?:[0-9] (?:\.[0-9] )?|[A-Za-z?])\z"

Details:

  • ^ - start of string
  • (?: - start of a non-capturing group:
    • [0-9] - one or more ASCII digits
    • (?:\.[0-9] )? - an optional occurrence of . and one or more ASCII digits
  • | - or
    • [A-Za-z?] - an ASCII letter or ?char
  • ) - end of the group
  • \z - the very end of string.

See a .NET regex demo online.

CodePudding user response:

if i got your use case right, then this might work:

^(\?|(\d \.?\d )|\S)$

Read it as: The word contains either one question mark, or a numeric value with propably a dot and numbers behind that or a single letter

You can try it our here: https://regex101.com/r/wLGJhJ/1

  • Related