I have a string in what is the best way to put the things in between $ inside a list in java?
String temp = $abc$and$xyz$;
how can i get all the variables within $ sign as a list in java
[abc, xyz]
i can do using stringtokenizer but want to avoid using it if possible.
thx
The pattern is simple enough that
String.splitshould work here, but in the more general case, one alternative forStringTokenizeris the much more powerfuljava.util.Scanner.The pattern to find is:
The
[…]is a character class. Something like[aeiou]matches one of any of the lowercase vowels.[^…]is a negated character class.[^aeiou]matches one of anything but the lowercase vowels.(…)is used for grouping.(pattern)is a capturing group and creates a backreference.The backslash preceding the
$(outside of character class definition) is used to escape the$, which has a special meaning as the end of line anchor. That backslash is doubled in aStringliteral:"\\"is aStringof length one containing a backslash).This is not a typical usage of
Scanner(usually the delimiter pattern is set, and tokens are extracted usingnext), but it does show how’d you usefindInLineto find an arbitrary pattern (ignoring delimiters), and then usingmatch()to access theMatchResult, from which you can get individual group captures.You can also use this
Patternin aMatcherfind()loop directly.Related questions
java.util.Scanner