开发者

Regex to match numbers, # @ % signs

I am trying to write a regex that matches all numbers (0-9) and # @ % signs.

I have tried ^[0-9#%@]$ , it doesn't work.

I want it to match, for example: 1234345, 2323, 1, 3@, %@, 9, 23743, @@@@@, or whatever...

There mus开发者_运维技巧t be something missing?

Thank you


You're almost right... All you're missing is something to tell the regular expression there may be more than once of those characters like a * (0 or more) or a + (1 or more).

^[0-9#%@]+$

The ^ and $ are used do indicate the start and end of a string, respectively. Make sure that you string only contains those characters otherwise, it won't work (e.g. "The number is 89#1" wouldn't work because the string begins with something other than 0-9, #, %, or @).


Your pattern ^[0-9#%@]$ only matches strings that are one character long. The [] construct matches a single character, and the ^ and $ anchors mean that nothing can come before or after the character matched by the [].

If you just want to know if the string has one of those characters in it, then [0-9#%@] will do that. If you want to match a string that must have at least one character in it, then use ^[0-9#%@]+$. The "+" means to match one or more of the preceding item. If you also want to match empty strings, then use [0-9#%@]*. The "*" means to match zero or more of the preceding item.


It should be /^[0-9#%@]+$/. The + is a qualifier that means "one or more of the preceding".

The problem with your current regex is that it will only match one character that could either be a number or #, %, or @. This is because the ^ and $ characters match the beginning and the end of the line respectively. By adding the + qualifier, you are saying that you want to match one or more of the preceding character-class, and that the entire line consists of one or more of the characters in the specified character-class.


remove the caret (^), it is used to match from the start of the string.


You forgot "+" ^[0-9#%@]+$ must work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜