Debugger
Debugger

Reputation: 564

Validate the Android version number in string is 3 or higher with regex

I need to validate that the Android version in a big string is more than 3.

In other words, "Android 2" will be invalid, but "Android 3" and "Android 7" will be correct.

Upvotes: 0

Views: 93

Answers (5)

Jess
Jess

Reputation: 8700

This wouldn't work?

$numberBiggerThanThree = preg_match('/([0-9]{2,}|[3-9])/', 'some long string 3');

Upvotes: 1

F.P
F.P

Reputation: 17831

preg_match('/some\s*string\s*([3-9][0-9]*|[1-9][0-9]+)/i', $haystack);

And here the working example

But, after examining your use-case, which seems to be checking for a specific version in an application description, I too would advise you to just get the number out of the string and compare it to an actual number to be sure it's larger or equal than 3:

preg_match('/([0-9]+)/', $string, $matches);
if ($matches[1] >= 3) {
  // Do something
}

Upvotes: 3

user1538943
user1538943

Reputation:

I modified Florian's solution:

[a-z]+\s?[a-z]+\s?([1-9][0-9]+|[3-9])

http://regexr.com?31ja1

It works for any string and not just "some string" and it allows only 0 or 1 whitespace character.

Upvotes: 1

hakre
hakre

Reputation: 197682

You match a word followed by an optional space and then the number greater than 2. Thanks to the decimal places you can control that:

(\w*\s*(?:[1-9]\d+|[3-9]))

Some little example (demo):

$subject = 'I have big string in that I need to check if number is present which is more than 3.
Means "some string2" will be invalid , but "some string 3","some string7" will be correct.';

$pattern = '(\w*\s*(?:[1-9]\d+|[3-9]))';

$r = preg_match_all($pattern, $subject, $matches);

var_dump($matches);

Output:

array(1) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "than 3"
    [1]=>
    string(8) "string 3"
    [2]=>
    string(7) "string7"
  }
}

I hope this is helpful.

Upvotes: 1

ghoti
ghoti

Reputation: 46836

Regex is for text matching, not arithmetic. Right tool for the right job...

preg_match('/([0-9]+)/', $string, $matches);
if ($matches[1] >= 3) {
  // Do something
}

Upvotes: 3

Related Questions