Timus83
Timus83

Reputation: 681

Regex to match -1:+1 pattern

How to make regex for -1:+1 pattern, where 1 is any integer?

I need to use it in preg_match(), but my regex skills are none...

Upvotes: 0

Views: 78

Answers (4)

shift66
shift66

Reputation: 11958

if you need real numbers (e.g. 001 should not be matched) use this pattern

/-([1-9]\d*|0):\+([1-9]\d*|0)/

| means or
[1-9] means one of the numbers between 1 and 9 (inclusive)
\d* means a digit 0 or more times

Upvotes: 0

Naveed S
Naveed S

Reputation: 5236

Use the following regex

-\d+:\+\d+

It matches a - followed by one or more digits followed by a : followed by a + followed by one or more digits.

Use the following if you want both to be the same integer

-(\d+):\+\1

Upvotes: 2

Huluk
Huluk

Reputation: 874

You can match single digits with \d. For 1 or more digits use \d+. You have to escape other characters, so it's \- and \+ for matching these characters. But I recommend reading a regex tutorial for the language you are using – it's not as hard as it looks!

Upvotes: 1

Himanshu
Himanshu

Reputation: 2454

<?php
$subject = "-100:+100";
$pattern = '/-\d+:\+\d+/';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>

\d refers to digit, + means one or more of preceding so \d+ is one or more digits and so on

Not Tested

Upvotes: 1

Related Questions