#regex issue
1 messages Β· Page 1 of 1 (latest)
ohhhhh
as you can see on regex101, it only matches the brackets, but not the whole string
that's why it returns false
if you wanna extract the brackets, you have to use a Pattern
something like this:
Pattern pattern = Pattern.compile("[<>\\[\\]]");
Matcher matcher = pattern.matcher("[map]");
oh, I see, so pattern is string.match but not whole string? or is it a configurable type thing using a different matcher
maybe explain what you are trying to achieve π
otherwise this is an XY problem lol
basically im creating a method that displays a command using a basecomponent, and when the message is clicked, it removes the [] and <> boxed items because they're not actual arguments, they're placeholders into a clickevent (suggest)
ah alright
so you want to do something like this:
[text] -> text
<text> -> text
right?
./world read <worldname> [config] -> /world read
ah okay so you wanna replace everything inside <> or [] brackets with "nothing"
right?
yeah, currently got this, seems to work using a maven test
String commandPlaintext;
StringBuilder commandPlaintextBuilder = new StringBuilder();
for (String element : commandText.split(" ")) {
if (!Pattern.compile("[<>\\[\\]]").matcher(element).find()) continue;
commandPlaintextBuilder.append(element).append(" ");
}
commandPlaintext = commandPlaintextBuilder.toString().trim();
thanks!
np!
btw
You can also use replaceAll
String string = "/world create [arg1] <arg2>";
System.out.println(string.replaceAll("<.*>","").replaceAll("\\[.*]",""));
this will simply print "/world create " (including the two spaces at the end)
oh interesting, thank you, didn't know replaceall could take regex π€
yeah it's a bit weird
String.replace takes a string to replace
String.replaceAll takes a regex
String.replaceFirst takes a regex too
:D?! java
but it's actually the same. String.replaceAll also uses a Pattern and Matcher internally π
this is the code for String.replaceAll:
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
interesting, why wouldnt they make replace regex too π€
well
replace is basically the same as replaceAll
just without regex support
I guess they added replace, then later they wanted to support regex so they added replaceFirst and replaceAll, i don't know π
I see, alright, well thank you for your help π
np, have a nice day :3