Wednesday 7 December 2016

java - Using regex to match variables in a string




I would like to match, using regex with groups, in java these scenarios but I am not very good with regex and don't understand how to match repeating things like these:



Text: local var1, var2, var3 = 100



I want to match to get all the lua variable names so my matches would be 'var1' and 'var2' and 'var3'



Text: self.var1, self.var2 = 200



Same as above but using self instead of local- I'd like matches of 'var1' and 'var2'




And lastly
Text: var1, var2, var3 = 300



I imagine I may be able to use the first regex for this, right? I'd like the matches to work for 1 or more matches so these all would work:



var1 = 10



var1, var2 = 10



self.v = 1




self.v1, self.v2 = 20



local v1,v2 = 10



local v1 = 30



I do not need all this in one big regex, 2 or 3 different patterns would work. (Hope this type of question is appropriate since I don't really have any code to show...)



Thanks in advance!



Answer



I think something like this should work



String input = "...Your input...";
List matches = new ArrayList<>();

Matcher m = Pattern.compile("(\\w+)\\s*(?=[,=])").matcher(input);
while(m.find()) {
matches.add(m.group(1));
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...