Saturday, 1 November 2014

Word boundary

Usually a regular expression match the word, even that is embedded in other word.

For Example
Enter Regular Expression
repeat
Enter the string
Don't repeat the repeated things
I found the text repeat starting at index 6 Ending at index 12
I found the text repeat starting at index 17 Ending at index 23

In the string 'Don't repeat the repeated things', regular expression matches the word twice, first one from the word 'repeat' and second one from the word 'repeated'.

By using '\b' you can specify the boundary for the word.

Enter Regular Expression
repeat\b
Enter the string
Don't repeat the repeated things
I found the text repeat starting at index 6 Ending at index 12

But the same regular expression match the word 'repeat' in the string 'prepeat'.

Enter the string
prepeat
I found the text repeat starting at index 1 Ending at index 7

So to exactly match the word 'repeat' use the regular expression '\brepeat\b'.

Enter Regular Expression
\brepeat\b
Enter the string
Don't repeat the repeated things
I found the text repeat starting at index 6 Ending at index 12

Enter the string
prepeat

Enter the string
repeat repeated
I found the text repeat starting at index 0 Ending at index 6





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment