For example, if the pattern I want to search for is apple
The string I want to search into is
apple apple@323 apple.. apple??...!! apple??%% Ilovesapple
Expected matches:
apple
apple..
apple??...!!
I want to match all the exact words, the only exception is that the word ends with the punctuation in
!,?.'"
Is this what you want ?
\bapple[!,?.'\"]*(?=\s+|$)
\b
word boundary for 'apple'apple
the pattern you want to search[!,?.'\"]*
zero or more occurrences of the special character(s) at the end that you want to match(?=\s+|$)
Positive Lookahead to ensure the matching word is followed by white space or end of line.Another possibility is this if you don't allow any non-space characters before 'apple':
(?:\s+|^)(apple[!,?.'\"]*)(?=\s+|$)
Regex Demo Note that @apple?
is not matched because it starts with @
Refer to Group 1
for the matches
(?:\s+|^)
non-capturing group for white space(s) or beginning of line before 'apple'
(
start of capturing group (captured into Group 1)
apple
the pattern you want to search[!,?.'\"]*
zero or more occurrences of the special character(s) at the end that you want to match)
end of capturing group (captured into Group 1)
(?=\s+|$)
Positive Lookahead to ensure the matching word is followed by white space or end of line.