Module: PIC

Defined in:
lib/standard/facets/pic.rb

Overview

PIC - Pattern matching based on COBOL-style Edited Pictures.

PIC provides a simple alternative to regular expressions for common data format matching. It uses single-character codes to describe the expected format of a string, inspired by COBOL’s PICTURE clause.

Picture Characters

The following picture characters are supported:

X - Any character (equivalent to regex `.`)
9 - Any digit (equivalent to regex `\d`)
Z - Zero or more digits (equivalent to regex `\d*`)
0 - Any digit (equivalent to regex `\d`)
A - Any letter, upper or lower case (equivalent to regex `[A-Za-z]`)
W - Any word character (equivalent to regex `\w`)
. - Literal period
, - Literal comma
- - Literal hyphen
/ - Literal forward slash

Repetition

Any picture character can be followed by a count in brackets:

9[3]       - Exactly 3 digits (e.g. `\d{3}`)
9[2,4]     - Between 2 and 4 digits (e.g. `\d{2,4}`)
9[2..4]    - Same as above, alternate syntax

Usage

require 'pic'

# Simple currency pattern
PIC['Z.99'].to_re        #=> /\d*\.\d\d/

# US phone number
PIC['9[3]-9[3]-9[4]'].to_re  #=> /\d{3}\-\d{3}\-\d{4}/

# Match against a string
PIC['99/99/9999'] =~ '12/25/2025'  #=> 0 (match)

Reference

Based on the concept of Edited Pictures from COBOL. See: www.csis.ul.ie/cobol/course/EditedPics.htm

Copyright © 2011 Rubyworks (BSD-2-Clause)

Defined Under Namespace

Classes: Template

Class Method Summary collapse

Class Method Details

.[](pic) ⇒ PIC::Template

Shortcut to ‘PIC::Template.new(pic)`.

Examples:

PIC['Z.99'].to_re  #=> /\d*\.\d\d/

Parameters:

  • pic (String)

    A picture string describing the expected format.

Returns:



62
63
64
# File 'lib/standard/facets/pic.rb', line 62

def self.[](pic)
  Template.new(pic)
end