tags:

views:

56

answers:

3

Can someone help me create this regex. I need it to check to see if the string is either entirely whitespace(empty) or if it only contains positive whole numbers. If anything else it fails. This is what I have so far.

/^\s*|[0-9][0-9]*/
+6  A: 

You're looking for:

/^(\s*|\d+)$/

If you want a positive number without leading zeros, use [1-9][0-9]*

If you don't care about whitespaces around the number, you can also try:

/^\s*\d*\s*$/

Note that you don't want to allow partial matching, for example 123abc, so you need the start and end anchors: ^...$.
Your regex has a common mistake: ^\s*|\d+$, for example, does not enforce a whole match, as is it the same as (^\s*)|(\d+$), reading, Spaces at the start, or digits at the end.

Kobi
your second example will only match whitespace if it's at the beginning or end ... it wouldn't match "1 2 3"
Cfreak
@Cfreak - correct. It does say *around* :)
Kobi
@Cfreak, why would you want to match `1 2 3`
Chad
I read it as whitespace or whole numbers. As in whitespace in the string doesn't matter
Cfreak
@Kobi - my bad!
Cfreak
That's cool. It's possible the OP wants to ignore all spaces. That's why you got my +1 - your answer is shorter. Also, the OP said "positive whole number **s** "
Kobi
Well, I suppose `^\s*([1-9]\d*\s*)+$` allows only spaces and positive numbers, but I'm just being silly.
Kobi
+1  A: 

You can try it-

/^\d*$/

To match with white space-

/^[\s\d\s]*$/
Sadat
that doesn't match whitespace
Cfreak
+1  A: 

Kobi has a good answer but technically you don't have to capture it (unless you're going to do something the output)

/^[\s\d]+$/

Or if you don't care if the string is completely empty (i.e. "")

/^[\s\d]*$/

To clarify I understood the original question to mean whitespace in the string should be ignored.

Cfreak
The problem with `/^[\s\d]*$/` is it matches things like `123 123`
Chad
Unless I'm mistaken, the group in Kobi's answer isn't for capturing the number, rather it's to keep the anchors (`^` and `$`) away from `|`
Wayne Conrad