Sunday, January 19, 2025
HomeProgrammingRegEx - Match Numbers of Variable Length

RegEx – Match Numbers of Variable Length

In regular expressions (RegEx), you can match numbers of variable length using quantifiers. Here’s a breakdown of how you can create patterns to match numbers with variable lengths.

Basic Syntax for Matching Numbers

  1. [0-9]: Matches a single digit (0 to 9).
  2. Quantifiers:
    • +: Matches one or more occurrences of the preceding token.
    • *: Matches zero or more occurrences.
    • {n}: Matches exactly n occurrences.
    • {n,}: Matches n or more occurrences.
    • {n,m}: Matches between n and m occurrences.

Examples

1. Match Any Number of Variable Length

To match numbers of any length (at least one digit):

[0-9]+

Example:

  • Input: "123 4567 89"
  • Matches: 123, 4567, 89

2. Match Numbers of Specific Length (e.g., 3 Digits)

To match numbers with exactly 3 digits:

[0-9]{3}

Example:

  • Input: "123 4567 89"
  • Matches: 123

3. Match Numbers of Length 3 or More

To match numbers with at least 3 digits:

[0-9]{3,}

Example:

  • Input: "123 4567 89"
  • Matches: 123, 4567

4. Match Numbers of Length Between 2 and 5

To match numbers with 2 to 5 digits:

[0-9]{2,5}

Example:

  • Input: "12 12345 678901"
  • Matches: 12, 12345

5. Match Optional Numbers (Zero or More Digits)

To match zero or more digits (e.g., 0, empty string, or longer numbers):

[0-9]*

Example:

  • Input: "123 abc"
  • Matches: 123, (and an empty match after abc)

Including Optional Decimal Points

To match numbers with optional decimal points (e.g., 123, 45.67):

[0-9]+(\.[0-9]+)?

Explanation:

  • [0-9]+: Matches one or more digits.
  • (\.[0-9]+)?: Matches an optional group containing a decimal point followed by one or more digits.
See also  Java Future Example

Example:

  • Input: "123 45.67 .89"
  • Matches: 123, 45.67

Match Signed Numbers (Positive/Negative)

To match signed numbers (e.g., +123, -45, 67):

[+-]?[0-9]+

Explanation:

  • [+-]?: Matches an optional + or - sign.
  • [0-9]+: Matches one or more digits.
See also  Learn Hibernate Tutorial

Example:

  • Input: "+123 -45 67"
  • Matches: +123, -45, 67

Use in Code

Here’s how you can use these patterns in Python:

import re

# Match numbers of variable length
pattern = r'[0-9]+'
text = "123 4567 89"
matches = re.findall(pattern, text)
print(matches)  # Output: ['123', '4567', '89']

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x