Home > Blockchain >  Regex for maximum 4 digit with or without decimal followed by N Or S
Regex for maximum 4 digit with or without decimal followed by N Or S

Time:04-19

I need a regex that allows a total of 5 Characters |Number followed by N or N.

prepared regex:

/^\h*(?:(?:\d|[1-9 ]{1,4})?)[NSns]$/gm

Problem statement:I am not able to add fraction point to regex

Valid Output:

1S
2N
1 S
1212S
1212s
1212N
1212n
1212n
121 n
121 N
121 s
121 S
12.22S
1.2N
12.2S
12.3 N

Invalid outputs:

123456S
12343S
122.122
12334.12

CodePudding user response:

You can use

^(?!(?:\D*\d){5})\s*\d (?:\.\d{1,2})?\s*[NSns]$

See the regex demo. Details:

  • ^ - start of string
  • (?!(?:\D*\d){5}) - no five digits allowed in the string
  • \s* - zero or more whitespaces (use [^\S\r\n]* if you need to stay on the same line)
  • \d - one or more digits
  • (?:\.\d{1,2})? - an optional sequence of . and one or two digits
  • \s* - zero or more whitespaces
  • [NSns] - N, S, n or s
  • $ - end of string.
  • Related