Jim Neath
Jim Neath

Reputation: 1217

Matching tabbed in blocks of text using regex

How can I match a block of text that is indented using tabs?

Say I have the following text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

    # This is a text block
    @some = 'ruby'
    @then = 'some more'

Aliquam malesuada scelerisque orci, sed venenatis sem eleifend ac. Vestibulum vehicula sagittis commodo. Praesent dapibus lacinia aliquam.

I want to match all the content that is tabbed in (ie. the code).

Upvotes: 1

Views: 305

Answers (2)

sepp2k
sepp2k

Reputation: 370397

This will return an array with one string per block:

str = %Q{
Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

\t# This is a text block
\t@some = 'ruby'
\t@then = 'some more'

Aliquam malesuada scelerisque orci, sed venenatis sem eleifend ac. Vestibulum vehicula sagittis commodo. Praesent dapibus lacinia aliquam.
\t# another block
\tfoo(bar)
}

str.scan(/(?:^\t.*\n)+/) #=> ["\t# This is a text block\n\t@some = 'ruby'\n\t@then = 'some more'\n", "\t# another block\n\tfoo(bar)\n"]

Upvotes: 3

Pinochle
Pinochle

Reputation: 5563

As long as you're not using multiline matches, you can get away with this: /^\t+.+/.

Upvotes: 0

Related Questions