Skip to content

Feat: Practical Examples of Regex Utility #211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

psychemist
Copy link

@psychemist psychemist commented Apr 1, 2025

🚀 Add Practical Regex Utility Examples for Cairo Development

🛠️ Issue

📖 Description

This PR introduces a comprehensive regex utility examples project that demonstrates practical usage of regular expressions in Cairo. The implementation provides working examples of pattern matching, text searching, replacement operations, and various regex features like wildcards, character classes, and quantifiers.

Technical Implementation Details

🔧 Regex Engine Compatibility

The implementation is designed to work with the simplified Cairo regex engine that supports:

  • Literal character matching
  • Character classes [a-z], [0-9] with range notation
  • Wildcards . for any character
  • Quantifiers ?, +, *
  • Basic pattern compilation and matching

🚫 Limitations Addressed

  • No repetition counts: Replaced {4} syntax with explicit repetition [0-9][0-9][0-9][0-9]
  • Simplified patterns: Used basic character classes instead of complex combinations
  • ByteArray cloning: Proper ownership handling to avoid move errors

📋 Configuration (Scarb.toml)

[dependencies]
starknet = "2.9.2"
regex = { path = "../../regex" }

[dev-dependencies]
snforge_std = "0.36.0"
assert_macros = "2.9.2"

🖼️ Screenshots

  • cargo test
Screenshot 2025-05-28 at 17 17 22

📝 Additional Notes

📁 Project Structure

Created a new utility examples project at regex_utils with the following structure:

utility_examples/
  └─ regex_utils/
       ├─ Scarb.toml                 # Project configuration with regex dependency
       ├─ src/
            ├─ lib.cairo             # Library module declaration
            ├─ main.cairo            # Main examples and demonstrations
            └─ tests/
                 └─ test_main.cairo  # Comprehensive test suite

🎯 Core Features Implemented

1. Email Pattern Matching (src/main.cairo)

  • Pattern: [a-z]+@[a-z]+.[a-z]+
  • Validates basic email format structure
  • Demonstrates boolean pattern matching

2. Text Search Operations

  • Find first occurrence: Locate the first email in text
  • Find all occurrences: Extract multiple email addresses from text
  • Position tracking with start/end indices

3. Text Replacement & Masking

  • Credit card number masking: 1234-5678-9012-3456XXXX-XXXX-XXXX-XXXX
  • SSN pattern replacement
  • Multiple pattern replacement in single text

4. Character Classes

  • Digit matching: [0-9]+ for number sequences
  • Letter matching: [a-z]+ for alphabetic text
  • Range-based character matching

5. Wildcard Patterns

  • Dot notation: c.t matches cat, cut, cot, cit
  • Flexible single-character matching

6. Quantifiers

  • Zero or one (?): colou?r matches both color and colour
  • One or more (+): a+ matches a, aa, aaa
  • Zero or more (*): Pattern repetition handling

🧪 Test Suite (src/tests/test_main.cairo)

Comprehensive test coverage with 7 test functions:

  1. test_new_and_matches - Basic regex creation and pattern matching
  2. test_find - First occurrence finding with position validation
  3. test_find_all - Multiple pattern matching and extraction
  4. test_replace - Text replacement and masking operations
  5. test_character_classes - Character class functionality
  6. test_wildcards - Wildcard pattern matching
  7. test_quantifiers - Quantifier behavior validation

Building and Running

🔨 Build the Project

cd examples/cairo/scripts/utility_examples/regex_utils
scarb build

🧪 Run the Test Suite

# Using Scarb
scarb test

# Using Starknet Foundry directly
snforge test

# Verbose output
snforge test --verbose

▶️ Run the Examples

# Execute the main examples
scarb cairo-run --package regex_utils

Example Usage

Basic Pattern Matching

let pattern: ByteArray = "[a-z]+@[a-z]+.[a-z]+";
let mut regex = RegexTrait::new(pattern);
let valid_email: ByteArray = "user@example.com";
assert!(regex.matches(valid_email), "Email should match pattern");

Text Search and Extraction

let text: ByteArray = "Contact us at support@company.com";
let result = regex.find(text);
// Returns: Some((14, 33)) - positions of the email

Pattern Replacement

let credit_card: ByteArray = "1234-5678-9012-3456";
let masked = regex.replace(credit_card, "XXXX-XXXX-XXXX-XXXX");
// Result: "XXXX-XXXX-XXXX-XXXX"

Benefits for Developers

  1. Learning Resource: Comprehensive examples of regex usage in Cairo
  2. Practical Applications: Real-world scenarios like email validation and data masking
  3. Test-Driven: Extensive test suite demonstrates proper usage patterns
  4. Performance Metrics: Gas usage tracking for optimization
  5. Foundation: Base for more complex pattern matching applications

Future Enhancements

  • Add more complex pattern examples
  • Performance benchmarking suite
  • Integration with validation utilities
  • Pattern library for common use cases
  • Documentation website generation

This implementation provides a solid foundation for regex operations in Cairo and serves as both educational material and practical utility for developers working with pattern matching in the ecosystem.

@coxmars
Copy link
Contributor

coxmars commented Apr 23, 2025

Hi @psychemist is this PR still in draft ? If not change that to merge it

@psychemist
Copy link
Author

@coxmars okay, i'll add remaining tests and update

@coxmars
Copy link
Contributor

coxmars commented Apr 27, 2025

@coxmars okay, i'll add remaining tests and update

cool, let me know when it is ready :)

@psychemist psychemist changed the title Feat: Add Regex Utility Examples Feat: Practical Examples of Regex Utility May 28, 2025
@psychemist psychemist marked this pull request as ready for review May 28, 2025 16:26
@psychemist
Copy link
Author

@coxmars this PR is ready for review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[FEAT]: Practical Examples of Regex Utility
2 participants