Can regex be used for cropping?

regex, regex-negation

Solution

The specifics depend on the language you are using, but here are a few common approaches for doing this with regex (code samples in Python):

Find all matches of your target string, and then combine each match into a single string:

>>> import re
>>> s = 'the quick brown quick fox'
>>> ''.join(re.findall('quick', s))
'quickquick'

Construct a regex to match everything except your target string, and then replace each match with an empty string (this is usually much more difficult than the other alternatives listed):

>>> re.sub('(?!quick|(?<=q)uick|(?<=qu)ick|(?<=qui)ck|(?<=quic)k).', '', s)
'quickquick'

Use capturing groups to match everything up until an occurrence of a target string, and then replace with just the target string:

>>> re.sub('.*?(quick|$)', r'\1', s)
'quickquick'

If your string has multiple lines as in your example, you can either split the strings on line breaks first or adapt the solutions to keep line breaks, for example:

>>> s = '''the quick brown fox
... the brown fox
... the quick brown quick fox'''
>>> print ''.join(re.findall('quick|[\r\n]', s))
quick

quickquick
>>> print re.sub('.*?(quick|$)', r'\1', s, flags=re.MULTILINE)
quick

quickquick

Problem

Let's say I have these three lines: ``` the quick brown fox the brown fox the quick brown quick fox ``` Can regex be used to crop out everything in each line except for the word `quick`? The end result would look like this: ``` quick quickquick ```

Original source