Find Words That Start With Slash Using Regex In Java

The method below matches all words that starts with a slash and no other slash should be found within the String. Using regex, I used a positive look behind approach that whenever a slash character is found, it should check if the previous character is a space character while the whole word should also be followed by a space character as well.

This way, the regex pattern ensures that the first chracter should be a slash and any characters following it are accepted such that there should be a space character at the end.

The regex does have a little limitation. What if the very first character of the String is a slash? Then it would not match that word because there is no previous space character before it. The only workaround for this one was to check if the String starts with a slash and if so, manually add a space character at the very first index of the String.

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *