right now i'm trying to learn how to use Matcher, Patterns and all that stuff, but i'm having a problem and i can't manage to solve it, i'm sure i'm doing something wrong but i don't know what, so i came here to ask for some help, here is my code:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("effect:([^:]*)(?::([^:]*))?(\\s)");
Matcher matcher = pattern.matcher("effect:health:10 effect:speed:15 ");
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
What im trying to make, is get from a string the effects and it's duration, but the effect duration isn't 100% necessary, right now the problem is that it does only detect the first effect, not the second one, it prints 'health' and '10', it needs an space at the end otherwhise it doesn't work, but if i remove '(\\s)' it won't work.
English isn't my native language, i tried to write this the best i could, if it have any misspelling i apologise.
First, since you don't seem to care about capturing the space, remove the capturing group about it.
Second, since the space may be optional, add a ?
.
Now, this will cause trouble, because [^:]
will consume the space, so also exclude spaces from the values being captured.
In reality, by doing that, you don't even need to match on the space at the end anyway, so remove it entirely.
Result:
Pattern.compile("effect:([^:\\s]*)(?::([^:\\s]*))?")
See result on regex101.
Since the regex find()
will just skip over "bad" data, you may want to add extra guard conditions, e.g. if the input is "supereffect:a:b:c:d"
, do you want to match and return a
/b
, or should it skip that.
To skip that, you can add guard condition saying, that matched pattern must:
(?<=^|\\s)
(?=\\s|$)
Pattern.compile("(?<=^|\\s)effect:([^:\\s]*)(?::([^:\\s]*))?(?=\\s|$)")