EasyRegex Logo
EasyRegex
New

How to Match a Number Using Regex (With Examples)

Regex (Regular Expressions) is a powerful tool for matching patterns in text. In this guide, you’ll learn how to match numbers using regex, with examples in multiple programming languages.

🔢 Basic Regex for Matching Numbers

1️⃣ Matching Whole Numbers (Integers)

If you need to match any positive whole number, use:

/\d+/

Example Matches: 123, 42, 987654 (❌ Does not match decimal numbers)

2️⃣ Matching Decimal Numbers

/\d+\.\d+/

Example Matches: 12.34, 0.99, 3.14159

3️⃣ Matching Negative Numbers

/-?\d+(\.\d+)?/

Example Matches: -123, -4.56, 0.99

🛠️ Regex for Different Programming Languages

✅ JavaScript

const regex = /-?\d+(\.\d+)?/g;
const text = "The price is -42.99 and the discount is 10";
console.log(text.match(regex)); 
    

✅ Python

import re
text = "Order 5 apples and 3.14 kg of sugar."
regex = r"-?\d+(\.\d+)?"
matches = re.findall(regex, text)
print(matches) 
    

🛠️ Try It Yourself!

Instead of manually testing regex patterns, use our interactive regex tester:

👉 Test Your Regex Here

🚨 Common Mistakes & Best Practices

  • Using `.` instead of `\.` (wrong: /\d+.+\d+/)
  • Forgetting to escape special characters (wrong: /\d+.\d+/)
  • Always use anchors (`^` and `$`) for full string validation

🚀 Conclusion

Regex is a powerful way to match numbers efficiently. Whether you're working with whole numbers, decimals, or negative values, understanding these patterns can save you time.

🔗 Try out these regex patterns live with our Regex Tester!

📌 Next Steps

  • ✅ Bookmark this guide for future reference.
  • ✅ Try these patterns in your own code.