Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Lookaround in Regular Expressions (See related posts)

What follows below is the output from an irb session to specifically try out Lookahead and Lookbehind in regex.

irb(main):002:0> "question"[/q(?=u)/]
=> "q"
irb(main):003:0> "qu>"[/qu(?=>)/]
=> "qu"
irb(main):004:0> "qu"[/qu(?=>)/]
=> nil
irb(main):006:0> "accumulator"[/(?=c)cumulator/]
=> "cumulator"
irb(main):007:0> "accumulator"[/a(?=c)cumulator/]
=> nil
irb(main):009:0> "abc"[/abc(?=c)/]
=> nil
irb(main):010:0> "abc"[/ab(?=c)/]
=> "ab"

irb(main):011:0> "abd"[/ab(?!c)/]
=> "ab"
irb(main):012:0> "abc"[/ab(?!c)/]
=> nil

irb(main):013:0> "abc"[/a(?<=b)c/] # lookbehind doesn't work in Ruby
SyntaxError: compile error
(irb):13: undefined (?...) sequence: /a(?<=b)c/
        from (irb):13
        from :0
irb(main):014:0> "abc"[/(?<=a)bc/] # lookbehind doesn't work in Ruby
SyntaxError: compile error
(irb):14: undefined (?...) sequence: /(?<=a)bc/
        from (irb):14
        from :0

irb(main):022:0> "how's the weather?"[/how.*(?=the)/]
=> "how's the wea"
irb(main):024:0> "how's the weather?"[/how.*(?=[the])/]
=> "how's the weath"
irb(main):025:0> "how's the weather?"[/how.*(?=t)/]
=> "how's the wea"
irb(main):037:0> "how's the weather?"[/how.+(?=\bt)/]
=> "how's "

irb(main):057:0> "how's the weather?"[/ho.*(?=[a-z])/]
=> "how's the weathe"
irb(main):061:0> "how's the weather?"[/ho.*(?=['])/]
=> "how"

reference: Regular Expressions Quick Start [regular-expressions.info]

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts