简体   繁体   中英

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:

  • <1
  • =2
  • 22>
  • >1
  • =00123456789

Examples that should not pass this reg. exp.:

  • <<2
  • ==222
  • <>=2

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 = .

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}

This should work.

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

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

Try this regex:

^\d+[=<>]$

Description

正则表达式可视化

这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM