localman
localman

Reputation: 497

Regex to allow number with leading special character

Here's what I've got so far: ^([<>0-9]{0,4}(\.[0-9]{1,4})?)?$

I need to allow the following:

1234.1234
.11
0.11
>11
<11
< 11

I need the following to fail:

12345.12345
12345
.12345
12>3
123<
>>123
<<123

I can't figure out the > and < parts to allow only once and only leading the string.

Thanks!

Upvotes: 2

Views: 56

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use this pattern:

^(?:[<>] ?)?(?:[0-9]{1,4}(?:\.[0-9]{1,4})?|\.[0-9]{1,4})$

demo

It ensures that there is at least one digit with this alternation:
[0-9]{1,4}(?:\.[0-9]{1,4})? | \.[0-9]{1,4}
and makes the space optional only if there is a < or a > at the start with:
^(?:[<>] ?)?

I assumed that capture groups are not needed so I used non-capturing groups instead: (?:...)

Note that to figure a literal dot you need to escape it: \.

Upvotes: 3

Eric Wendelin
Eric Wendelin

Reputation: 44349

I think ^[<>]?\s?(\d{,4})?\.?(\d{1,4})?$ should do it.

You can use http://regexpal.com to help you verify.

Upvotes: 0

Related Questions