简体   繁体   English

从字符串中提取变量和值

[英]Extract varaibles and values from a string

I have a string that looks like this: String info = "var1=value1;var2=value2;var3=value3;" 我有一个看起来像这样的字符串:String info =“ var1 = value1; var2 = value2; var3 = value3;” ; ;

What would be your approach to extract each var name and value in Java? 用Java提取每个变量名称和值的方法是什么?

Any ideas would be appreciated, 任何想法,将不胜感激,

Thanks! 谢谢!

You can try using following regex, 您可以尝试使用以下正则表达式,

(\w+)=(\w+);

Working Demo 工作演示

It uses the concept of Group capture 它使用组捕获的概念

Another user asked a similar question. 另一个用户问了类似的问题。 The user wanted to know how to parse a string "A=B&C=D&E=F" into a map. 用户想知道如何将字符串“ A = B&C = D&E = F”解析到映射中。 Your string looks almost the same. 您的字符串看起来几乎一样。 It got keys and values too. 它也有键和值。

Using a map would be the easiest way to have a clear structure. 使用地图将是拥有清晰结构的最简单方法。 Take a look at the following question and the provided answer: 查看以下问题和提供的答案:

How to parse the string into map 如何将字符串解析为map

Extracted part of the answer: 提取部分答案:

I would use split 我会用分裂

 String text = "A=B&C=D&E=F"; Map<String, String> map = new LinkedHashMap<String, String>(); for(String keyValue : text.split(" *& *")) { String[] pairs = keyValue.split(" *= *", 2); map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]); } 

EDIT allows for padded spaces and a value with an = or no value. EDIT允许填充空格以及带有=或无值的值。 eg 例如

A = minus- & C=equals= & E==F

It shows how you could split a string like yours in key-value pairs and save those in a map. 它显示了如何将像您这样的字符串拆分为键值对,并将其保存在映射中。

This would be my choice to split your string and storage the information. 我将选择拆分字符串并存储信息。

I would probably just go with String.split() (untested): 我可能会只使用String.split()(未经测试):

for (String s : info.split(":") {
     String[] pair = s.split("=");
     HashMap.put(pair[0],pair[1]);     // Or whatever you do with the data
}

Thanks for helping me out with this. 感谢您帮助我解决此问题。 I have read about regex and I'm more familiar with it now. 我已经阅读了有关正则表达式的内容,现在对此更加熟悉。 I admit I should go through the tutorials first before I asked the question (lesson learned). 我承认在问这个问题(经验教训)之前,我应该先阅读教程。 I was bit under pressure so that was easier was just ask someone :) 我有点压力,要轻松些就问一个人:)
I have used the method suggested Hudi: 我已经使用了建议的方法胡迪:


    public class ArduinoResponsePhraser {

        Map varMap = new HashMap();

        public Map PhraseString(String response)
        {
                for (String s : response.split(";")) {
                        String[] pair = s.split("=");
                        varMap.put(pair[0], pair[1]);
                }
                return varMap;
        }

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

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