Regex 101

From bibbleWiki
Jump to navigation Jump to search

Testing

echo "My stuff" | grep "^My"

Examples

Starts with

echo "A" |grep "^A" 
echo "AAAAAAAAAAA" |grep "^A"

Starts with any number of As and Ends With

echo "AAAAAAAAAAAB" |grep "^A*B$

Word Boundries

Was not sure what this meant but what it means is a word in a sentence e.g. quick brown fox so this would be a match

echo "quick brown fox jumps over" |grep "\bfox\b"

And this would not be a match

echo "quick brownfoxjumps over" |grep "\bfox\b"
echo "quick brown foxjumps over" |grep "\bfox\b"
echo "quick brownfox jumps over" |grep "\bfox\b"

Match Start and End with anything in the middle

Ran into trouble with this as I found grep does not work like the examples

^Me matches beginning
s+(.*?)\s+ matches everything from space to last space
Fred$ makes sure the phrase ends in Fred

Using grep fails, using egrep works

echo "Me grindurr 9 51 19 3 7 1 2 2 Fred" |egrep "^Me\s+(.*?)\s+Fred$"

In egrep (.*?) matches any character. It turned out the \s+ was the problem and this works

echo "Me grindurr 9 51 19 3 7 1 2 2 Fred" |egrep "^Me\s(.*?)\sFred$"