Java regular expressions replace all words without replacing all words
•
Java
I have been using this regular expression in Java for many years and can't make it work:
(?:^| )(?:the|and|at|in|or|on|off|all|beside|under|over|next)(?: |$)
following:
pattern.matcher("the cat in the hat").replaceAll(" ")
Gave me a cat hat Another example input is the cat with the next hat. It gives me the cat with the next hat
Is there any way to make this regular expression replacement work without breaking them into multiple separate regular expressions for each word and trying to replace the string repeatedly?
Solution
Yes, you can do this easily. You just need to use boundaries, which is what you want to describe: (?: ^ |) just do this:
\b(?:the|and|at|in|or|on|off|all|beside|under|over|next)\b
Your original file was not captured, but as mentioned in the comments, if you want to capture options, you can use capture instead of non capture groups:
\b(the|and|at|in|or|on|off|all|beside|under|over|next)\b
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码