- README

- Top Level Namespace
- Adler32
- ArgumentError
- Array
- Atomic
- Base64
  - Error
- Benchmark
  - BM
    - Job
    - Tms
  - IPS
    - Entry
    - Job
- BigFloat
- BigInt
- BigRational
- BitArray
- Bool
- Box
- Bytes
- Channel
  - Buffered
  - ClosedError
  - ReceiveAction
  - SelectAction
  - SendAction
  - Unbuffered
- Char
  - Reader
- Class
- Colorize
  - Object
  - ObjectExtensions
- Comparable
- Complex
- Concurrent
  - CanceledError
- CRC32
- Crypto
  - Bcrypt
    - Error
    - Password
  - Blowfish
  - Subtle
- Crystal
  - Macros
    - And
    - Arg
    - ArrayLiteral
    - Assign
    - ASTNode
    - BinaryOp
    - Block
    - BoolLiteral
    - Call
    - Case
    - Cast
    - CharLiteral
    - ClassDef
    - ClassVar
    - Def
    - Expressions
    - Generic
    - Global
    - HashLiteral
    - If
    - ImplicitObj
    - InstanceSizeOf
    - InstanceVar
    - IsA
    - Macro
    - MacroId
    - MetaVar
    - MultiAssign
    - NamedArgument
    - NamedTupleLiteral
    - NilableCast
    - NilLiteral
    - Nop
    - Not
    - NumberLiteral
    - Or
    - Out
    - Path
    - PointerOf
    - RangeLiteral
    - ReadInstanceVar
    - RegexLiteral
    - Require
    - RespondsTo
    - SizeOf
    - Splat
    - StringInterpolation
    - StringLiteral
    - SymbolLiteral
    - TupleLiteral
    - TypeDeclaration
    - TypeNode
    - UnaryExpression
    - UninitializedVar
    - Union
    - Var
    - VisibilityModifier
    - When
    - While
  - System
- CSV
  - Builder
    - Row
  - Error
  - Lexer
  - MalformedCSVError
  - Parser
  - Row
  - Token
    - Kind
- Debug
  - DWARF
    - Abbrev
      - Attribute
    - AT
    - FORM
    - Info
      - Value
    - LineNumbers
      - Register
      - Row
      - Sequence
    - LNE
    - LNS
    - Strings
    - TAG
  - ELF
    - Endianness
    - Error
    - Ident
    - Klass
    - Machine
    - OSABI
    - SectionHeader
      - Flags
      - Type
    - Type
- Deque
- Digest
  - Base
  - MD5
  - SHA1
- Dir
- DivisionByZero
- DL
- ECR
- Enum
- Enumerable
  - EmptyError
- ENV
- Errno
- Exception
- Fiber
- File
  - Stat
- FileUtils
- Flate
  - Error
  - Reader
  - Strategy
  - Writer
- Float
  - Primitive
  - Printer
    - CachedPowers
      - Power
    - DiyFP
    - Grisu3
    - IEEE
- Float32
- Float64
- GC
  - Stats
- Gzip
  - Error
  - Header
  - Reader
  - Writer
- Hash
- HTML
- HTTP
  - Client
    - BodyType
    - Response
  - CompressHandler
  - ComputedContentTypeHeader
  - Cookie
  - Cookies
  - ErrorHandler
  - FormData
    - Builder
    - Error
    - FileMetadata
    - Parser
    - Part
  - Handler
    - Proc
  - Headers
  - LogHandler
  - Multipart
    - Builder
    - Error
    - Parser
  - Params
    - Builder
  - Request
  - Server
    - Context
    - RequestProcessor
    - Response
  - StaticFileHandler
    - DirectoryListing
  - WebSocket
  - WebSocketHandler
- Indexable
- IndexError
- INI
- Int
  - Primitive
  - Signed
  - Unsigned
- Int16
- Int32
- Int64
- Int8
- InvalidByteSequenceError
- IO
  - Buffered
  - ByteFormat
    - BigEndian
    - LittleEndian
    - NetworkEndian
    - SystemEndian
  - Delimited
  - EncodingOptions
  - EOFError
  - Error
  - FileDescriptor
  - Hexdump
  - Memory
  - MultiWriter
  - Seek
  - Sized
  - Timeout
- IPSocket
- Iterable
- Iterator
  - IteratorWrapper
  - Stop
- JSON
  - Any
  - Builder
    - ArrayState
    - DocumentEndState
    - DocumentStartState
    - ObjectState
    - StartState
    - State
  - Error
  - Lexer
  - ParseException
  - Parser
  - PullParser
  - Token
  - Type
- KeyError
- Levenshtein
  - Finder
- LLVM
  - ABI
    - AArch64
    - ArgKind
    - ArgType
    - ARM
    - FunctionType
    - X86
    - X86_64
      - RegClass
  - AtomicOrdering
  - AtomicRMWBinOp
  - Attribute
  - AttributeIndex
  - BasicBlock
  - BasicBlockCollection
  - Builder
  - CallConvention
  - CodeGenFileType
  - CodeGenOptLevel
  - CodeModel
  - Context
  - DIBuilder
  - DIFlags
  - DwarfTag
  - DwarfTypeEncoding
  - Function
  - FunctionCollection
  - FunctionPassManager
    - Runner
  - GenericValue
  - GlobalCollection
  - InstructionCollection
  - IntPredicate
  - JITCompiler
  - Linkage
  - MemoryBuffer
  - Module
  - ModuleFlag
  - ModulePassManager
  - OperandBundleDef
  - ParameterCollection
  - PassManagerBuilder
  - PassRegistry
  - PhiTable
  - RealPredicate
  - RelocMode
  - Target
  - TargetData
  - TargetMachine
  - Type
    - Kind
  - Value
    - Kind
  - ValueMethods
  - VerifierFailureAction
- Logger
  - Formatter
  - Severity
- Markdown
  - HTMLRenderer
  - Parser
    - PrefixHeader
    - UnorderedList
  - Renderer
- Math
- Mutex
- NamedTuple
- Nil
- Number
  - Primitive
- OAuth
  - AccessToken
  - Consumer
  - Error
  - RequestToken
- OAuth2
  - AccessToken
    - Bearer
    - Mac
  - Client
  - Error
  - Session
- Object
- OpenSSL
  - Digest
    - Error
    - UnsupportedError
  - DigestBase
  - DigestIO
    - DigestMode
  - Error
  - HMAC
  - MD5
  - SHA1
  - SSL
    - Context
      - Client
      - Server
    - Error
    - ErrorType
    - Modes
    - Options
    - Socket
      - Client
      - Server
    - VerifyMode
    - X509VerifyFlags
- OptionParser
  - Exception
  - InvalidOption
  - MissingOption
- PartialComparable
- Pointer
  - Appender
- PrettyPrint
- Proc
- Process
  - Env
  - Status
  - Stdio
  - Tms
- Random
  - ISAAC
  - MT19937
  - PCG32
  - System
- Range
- Readline
  - CompletionProc
  - KeyBindingProc
- Reference
- Reflect
- Regex
  - MatchData
  - Options
- SecureRandom
- Set
- Signal
- Slice
- Socket
  - Address
  - Addrinfo
  - Error
  - Family
  - IPAddress
  - Protocol
  - Server
  - Type
  - UNIXAddress
- Spec
  - Expectations
  - Methods
  - ObjectExtensions
- StaticArray
- String
  - Builder
  - RawConverter
- StringPool
- StringScanner
- Struct
- Symbol
- System
- TCPServer
- TCPSocket
- Tempfile
- Termios
  - AttributeSelection
  - BaudRate
  - ControlMode
  - InputMode
  - LineControl
  - LocalMode
  - OutputMode
- Time
  - DayOfWeek
  - EpochConverter
  - EpochMillisConverter
  - Format
    - Error
  - Kind
  - MonthSpan
  - Span
- Tuple
- TypeCastError
- UDPSocket
- UInt16
- UInt32
- UInt64
- UInt8
- Unicode
  - CaseOptions
- Union
- UNIXServer
- UNIXSocket
- URI
  - Error
- Value
- WeakRef
- XML
  - Attributes
  - AttributeType
  - Builder
  - Error
  - HTMLParserOptions
  - Namespace
  - Node
  - NodeSet
  - ParserOptions
  - Reader
  - SaveOptions
  - Type
  - XPathContext
- YAML
  - Any
  - Builder
  - Error
  - EventKind
  - ParseException
  - Parser
  - PullParser
  - Type
- Zip
  - CompressionMethod
  - Error
  - File
    - Entry
  - FileInfo
  - Reader
    - Entry
  - Writer
    - Entry
- Zlib
  - Error
  - Reader
  - Writer

# class StringScanner

- StringScanner
- Reference
- Object

## Overview

`StringScanner` provides for lexical scanning operations on a `String`.

### Example

    require "string_scanner"

    s = StringScanner.new("This is an example string")
    s.eos? # => false

    s.scan(/\w+/) # => "This"
    s.scan(/\w+/) # => nil
    s.scan(/\s+/) # => " "
    s.scan(/\s+/) # => nil
    s.scan(/\w+/) # => "is"
    s.eos?        # => false

    s.scan(/\s+/) # => " "
    s.scan(/\w+/) # => "an"
    s.scan(/\s+/) # => " "
    s.scan(/\w+/) # => "example"
    s.scan(/\s+/) # => " "
    s.scan(/\w+/) # => "string"
    s.eos?        # => true

    s.scan(/\s+/) # => nil
    s.scan(/\w+/) # => nil

Scanning a string means remembering the position of a scan offset, which is just an index. Scanning moves the offset forward, and matches are sought after the offset; usually immediately after it.

### Method Categories

Methods that advance the scan offset:

- `#scan`
- `#scan_until`
- `#skip`
- `#skip_until`

Methods that look ahead:

- `#peek`
- `#check`
- `#check_until`

Methods that deal with the position of the offset:

- `#offset`
- `#offset=`
- `#eos?`
- `#reset`
- `#terminate`

Methods that deal with the last match:

- `#[]`
- `#[]?`

Miscellaneous methods:

- `#inspect`
- `#string`

## Defined in:

## Constructors

- .new(str : String)

## Instance Method Summary

- #[](n)

  Returns the n-th subgroup in the most recent match.

- #[]?(n)

  Returns the nilable n-th subgroup in the most recent match.

- #check(pattern)

  Returns the value that `#scan` would return, without advancing the scan offset.

- #check_until(pattern)

  Returns the value that `#scan_until` would return, without advancing the scan offset.

- #eos?

  Returns `true` if the scan offset is at the end of the string.

- #inspect(io : IO)

  Writes a representation of the scanner.

- #offset

  Returns the current position of the scan offset.

- #offset=(position : Int)

  Sets the position of the scan offset.

- #peek(len)

  Extracts a string corresponding to string[offset,len], without advancing the scan offset.

- #reset

  Resets the scan offset to the beginning and clears the last match.

- #rest

  Returns the remainder of the string after the scan offset.

- #scan(pattern)

  Tries to match with pattern at the current position.

- #scan_until(pattern)

  Scans the string until the pattern is matched.

- #skip(pattern)

  Attempts to skip over the given pattern beginning with the scan offset.

- #skip_until(pattern)

  Attempts to skip until the given pattern is found after the scan offset.

- #string : String

  Returns the string being scanned.

- #terminate

  Moves the scan offset to the end of the string and clears the last match.

### Instance methods inherited from class `Reference`

==(other : self)
==(other) ==, dup dup, hash hash, inspect(io : IO) : Nil inspect, object_id : UInt64 object_id, pretty_print(pp) : Nil pretty_print, same?(other : Reference)
same?(other : Nil) same?, to_s(io : IO) : Nil to_s

### Constructor methods inherited from class `Reference`

new new

### Instance methods inherited from class `Object`

!=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other) ===, =~(other) =~, class class, dup dup, hash hash, inspect(io : IO)
inspect inspect, itself itself, not_nil! not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, tap(&block) tap, to_json(io : IO)
to_json to_json, to_pretty_json(indent : String = " ")
to_pretty_json(io : IO, indent : String = " ") to_pretty_json, to_s
to_s(io : IO) to_s, to_yaml(io : IO)
to_yaml to_yaml, try(&block) try, unsafe_as(type : T.class) forall T unsafe_as

### Constructor methods inherited from class `Object`

from_json(string_or_io, root : String) : self
from_json(string_or_io) : self from_json, from_yaml(string_or_io) : self from_yaml

## Constructor Detail

def self.new(str : String) #

## Instance Method Detail

def [](n) #

Returns the n-th subgroup in the most recent match.

Raises an exception if there was no last match or if there is no subgroup.

    s = StringScanner.new("Fri Dec 12 1975 14:39")
    regex = /(?<wday>\w+) (?<month>\w+) (?<day>\d+)/
    s.scan(regex) # => "Fri Dec 12"
    s[0]          # => "Fri Dec 12"
    s[1]          # => "Fri"
    s[2]          # => "Dec"
    s[3]          # => "12"
    s["wday"]     # => "Fri"
    s["month"]    # => "Dec"
    s["day"]      # => "12"

def []?(n) #

Returns the nilable n-th subgroup in the most recent match.

Returns `nil` if there was no last match or if there is no subgroup.

    s = StringScanner.new("Fri Dec 12 1975 14:39")
    regex = /(?<wday>\w+) (?<month>\w+) (?<day>\d+)/
    s.scan(regex)  # => "Fri Dec 12"
    s[0]?          # => "Fri Dec 12"
    s[1]?          # => "Fri"
    s[2]?          # => "Dec"
    s[3]?          # => "12"
    s[4]?          # => nil
    s["wday"]?     # => "Fri"
    s["month"]?    # => "Dec"
    s["day"]?      # => "12"
    s["year"]?     # => nil
    s.scan(/more/) # => nil
    s[0]?          # => nil

def check(pattern) #

Returns the value that `#scan` would return, without advancing the scan offset. The last match is still saved, however.

    s = StringScanner.new("this is a string")
    s.offset = 5
    s.check(/\w+/) # => "is"
    s.check(/\w+/) # => "is"

def check_until(pattern) #

Returns the value that `#scan_until` would return, without advancing the scan offset. The last match is still saved, however.

    s = StringScanner.new("test string")
    s.check_until(/tr/) # => "test str"
    s.check_until(/g/)  # => "test string"

def eos? #

Returns `true` if the scan offset is at the end of the string.

    s = StringScanner.new("this is a string")
    s.eos?                # => false
    s.scan(/(\w+\s?){4}/) # => "this is a string"
    s.eos?                # => true

def inspect(io : IO) #

Writes a representation of the scanner.

Includes the current position of the offset, the total size of the string, and five characters near the current position.

def offset #

Returns the current position of the scan offset.

def offset=(position : Int) #

Sets the position of the scan offset.

def peek(len) #

Extracts a string corresponding to string[offset,len], without advancing the scan offset.

def reset #

Resets the scan offset to the beginning and clears the last match.

def rest #

Returns the remainder of the string after the scan offset.

    s = StringScanner.new("this is a string")
    s.scan(/(\w+\s?){2}/) # => "this is "
    s.rest                # => "a string"

def scan(pattern) #

Tries to match with pattern at the current position. If there's a match, the scanner advances the scan offset, the last match is saved, and it returns the matched string. Otherwise, the scanner returns `nil`.

    s = StringScanner.new("test string")
    s.scan(/\w+/)   # => "test"
    s.scan(/\w+/)   # => nil
    s.scan(/\s\w+/) # => " string"
    s.scan(/.*/)    # => nil

def scan_until(pattern) #

Scans the string until the pattern is matched. Returns the substring up to and including the end of the match, the last match is saved, and advances the scan offset. Returns `nil` if no match.

    s = StringScanner.new("test string")
    s.scan_until(/tr/) # => "test str"
    s.scan_until(/tr/) # => nil
    s.scan_until(/g/)  # => "ing"

def skip(pattern) #

Attempts to skip over the given pattern beginning with the scan offset. In other words, the pattern is not anchored to the current scan offset.

If there's a match, the scanner advances the scan offset, the last match is saved, and it returns the size of the skipped match. Otherwise it returns `nil` and does not advance the offset.

This method is the same as `#scan`, but without returning the matched string.

def skip_until(pattern) #

Attempts to skip until the given pattern is found after the scan offset. In other words, the pattern is not anchored to the current scan offset.

If there's a match, the scanner advances the scan offset, the last match is saved, and it returns the size of the skip. Otherwise it returns `nil` and does not advance the offset.

This method is the same as `#scan_until`, but without returning the matched string.

def string : String #

Returns the string being scanned.

def terminate #

Moves the scan offset to the end of the string and clears the last match.