Regular Expression

https://github.com/nntrn/save/issues/55

Created on


Lookahead & lookbehind

# Capture an entire line that contains a word
(?=.*WORD).*

# Capture an entire line that contains two words in any order
(?=.*WORD1)(?=.*WORD2).*

# Capture entire lines that contain either WORD[1-3] from left to right
(?=.*WORD1|WORD2|WORD3).*

Capture entire lines that contain WORD[1-3] from left to right 
(.*?=WORD1|WORD2|WORD3).*

# Capture every word in the string EXCEPT the words in the list
(?>[\w-]+)(?<!WORD1|WORD2|WORD3|WORD4)

# Capture every part of the string that comes before WORD
.*(?=WORD)

# Capture every part of the string that comes after WORD
(?<=WORD).*

# Capture every part of the string that comes between two words
(?<=WORD1).*(?=WORD2)

# Captures the first word after WORD
(?<=WORD)\s+(\w+)

# Captures the words on either side (left and right) of the word WORD 
\w+(?=\sWORD)|(?<=WORD\s)\w+

Word Boundaries

# Capture a phrase if it exists in the string and return that phrase
\b(To Be Or Not To Be)\b

# Capture a phrase if it exists in a string (this one does not use word boundaries so it must account for blank spaces)
(To\sBe\sOr\sNot\sTo\sBe)

# Capture any word that appears twice in a string
(\b\w+\b)(?=[\s\S]*\b\1\b)

# Capture any phrase that appears twice in a string
(\b\w+\s+\S+\b)(?=[\s\S]*\b\1\b)

Source