OutOfSpaceHoneyBadger
OutOfSpaceHoneyBadger

Reputation: 1048

Regexp: numbers and few special characters

I am buried in a RegExp hell and can't find way out, please help me.

I need RegExp that matches only numbers (at least 1 number) and one of this characters: <, >, = (exactly one of them one time).

My reg. expression looks like this:

^[0-9]+$|^[=<>]{1}$

And I thought it should match when my string containts one or more digits and exactly 1 special character defined by me. But it doesn't act correctly. I think there might be problem with my start/end of string definition but Im not sure about that.

Examples that should pass include:

Examples that should not pass this reg. exp.:

Upvotes: 2

Views: 624

Answers (6)

Herrington Darkholme
Herrington Darkholme

Reputation: 6315

This one:

/^\d+[<>=]$|^[<>=]\d+$/

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149078

I thought it should match when my string containts one or more digits and exactly 1 special character

No, the original pattern matches a string contains one or more digits or exactly 1 special character. For example it will match 123 and = but not 123=.

Try this pattern:

^\d+[=<>]$

This will match that consists of one or more digits, followed by exactly one special character. For example, this will match 123= but not 123 or =.

If you want your special character to appear before the number, use a pattern like this instead:

^[=<>]\d+$

This will match =123 but not 123 or =.


Update

Given the examples you provided, it looks like you want to match any string which contains one or more digits and exactly one special character either at the beginning or the end. In that case use this pattern:

^([=<>]\d+|\d+[=<>])$

This will match <1, =2, 22>, and >1, but not 123 or =.

Upvotes: 2

Stephan
Stephan

Reputation: 43083

Try this regex:

^\d+[=<>]$

Description

Regular expression visualization

Upvotes: 1

This should work.

^[0-9]+[=<>]$

1 or more digits followed by "=<>".

Upvotes: 1

M21B8
M21B8

Reputation: 1887

Your regex says:

1 or more numbers OR 1 symbol

Also, the ^ and $ means the whole string, not contains. if you want a contains, drop them. I don't know if you have a space between the number and symbol, so put in a conditional space:

[0-9]+\s?[=<>]{1}

Upvotes: 1

zavg
zavg

Reputation: 11081

Just use [0-9]+[=<>]

Here are visualizers of your regexp and this one:

Upvotes: 1

Related Questions