I am new to regex. I have this regex:
\[(.*[^(\]|\[)].*)\]
Basically it should take this:
[[a][b][[c]]]
And be able to replace with:
[dd[d]]
abc, d are unrelated. Needless to say the regex bit isn't working. it replaces the entire string with "d" in this case.
Any explanation or aid would be great!
EDIT:
I tried another regex,
\[([^\]]{0})\]
This one worked for the case where brackets contain no inner brackets and nothing else inside. But it doesn't work for the described case.
If you want to remove the [ or the ] , use the expression: "\\[|\\]" . The two backslashes escape the square bracket and the pipe is an "or".
The [] construct in a regex is essentially shorthand for an | on all of the contents. For example [abc] matches a, b or c. Additionally the - character has special meaning inside of a [] . It provides a range construct. The regex [a-z] will match any letter a through z.
Square brackets match something that you kind of don't know about a string you're looking for. If you are searching for a name in a string but you're not sure of the exact name you could use instead of that letter a square bracket. Everything you put inside these brackets are alternatives in place of one character.
Just make sure ] is the first character (or in this case, first after the ^ . result2 = Regex. Replace(result2, "[^][A-Za-z0-9/.,>#:\s]", "");
You need to know that .
dot is special character which represents "any character beside new line mark" and *
is greedy so it will try to find maximal match.
In your regex \[(.*[^(\]|\[)].*)\]
first .*
will represent maximal set of characters between [
and [^(\]|\[)].*)\]]
and this part can be understood as non [
or ]
character, optional other characters .*
and finally ]
. So this regex will match your entire input.
To get rid of that problem remove both .*
from your regex. Also you don't need to use |
or (
)
inside [^...]
.
System.out.println("[[a][b][[c]]]".replaceAll("\\[[^\\]\\[]\\]", "d"));
Output: [dd[d]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With