简体   繁体   English

使用正则表达式匹配字符串中的变量

[英]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: 我想在组这些情况下在Java中使用正则表达式进行匹配,但我对正则表达式不太满意,并且不了解如何匹配重复的此类代码:

Text: local var1, var2, var3 = 100 文字: 本地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' 我想进行匹配以获取所有lua变量名称,因此我的匹配项将为“ var1”,“ var2”和“ var3”

Text: self.var1, self.var2 = 200 文字: self.var1,self.var2 = 200

Same as above but using self instead of local- I'd like matches of 'var1' and 'var2' 与上述相同,但使用self而不是local-我希望匹配“ var1”和“ var2”

And lastly Text: var1, var2, var3 = 300 最后是文本: 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: 我希望火柴能用于1个或多个火柴,因此所有这些都可以工作:

var1 = 10 var1 = 10

var1, var2 = 10 var1,var2 = 10

self.v = 1 self.v = 1

self.v1, self.v2 = 20 self.v1,self.v2 = 20

local v1,v2 = 10 本地v1,v2 = 10

local v1 = 30 本地v1 = 30

I do not need all this in one big regex, 2 or 3 different patterns would work. 我不需要一个大的正则表达式中的所有这些,可以使用2或3种不同的模式。 (Hope this type of question is appropriate since I don't really have any code to show...) (希望这种类型的问题是适当的,因为我实际上没有任何代码可以显示...)

Thanks in advance! 提前致谢!

I think something like this should work 我认为这样的事情应该起作用

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM