I'm trying to remove some words from the line. I don't want to prescribe them but replace them, because the words that I remove may increase. So I used an array. But when I try to do this, I get errors. I will be glad of any help.
String[] a = new String[]{
"\\bof \\b",
"\\bor \\b "," \\bit \\b "," \\bto \\b "
};
String str = "asdasdas of or asdasd";
str = str.replaceAll(
Arrays.toString(a)
, "");
This is a partial answer..
Problem #1: The
Arrays.toString(a)
returns a string which is bounded by[]
so this is the result:The brackets are special to regex to define the start-end of a character class definition.
\b
in a character class definition does not mean "word boundary" but rather results in an "illegal escape sequence".So first step is to remove the brackets from the regex string (from here).
Problem #2: Your regex now looks like:
This is not likely what you want - here's what I interpret what you want:
(Note also the space after the expressions which should be removed.)
So assume we start with:
So to implement the "OR" part you need:
And so the replace operation would look like:
To continue using your array approach you could then use:
which yields the regex from your array (same as discussed before):
And so
yields:
I was a bit loose in the treatment of regex explanation so I would invite others to be more precise in their answers.
Good luck.