簡體   English   中英

Java字符串解析 - {k1 = v1,k2 = v2,...}

[英]Java String parsing - {k1=v1,k2=v2,…}

我有以下字符串,可能包含約100個條目:

String foo = "{k1=v1,k2=v2,...}"

我正在尋找以下功能:

String getValue(String key){
    // return the value associated with this key
}

我想在不使用任何解析庫的情況下執行此操作。 什么想法快速的東西?

如果您知道您的字符串將始終如下所示,請嘗試以下操作:

HashMap map = new HashMap();

public void parse(String foo) {
  String foo2 = foo.substring(1, foo.length() - 1);  // hack off braces
  StringTokenizer st = new StringTokenizer(foo2, ",");
  while (st.hasMoreTokens()) {
    String thisToken = st.nextToken();
    StringTokenizer st2 = new StringTokenizer(thisToken, "=");

    map.put(st2.nextToken(), st2.nextToken());
  }
}

String getValue(String key) {
  return map.get(key).toString();
}

警告:我實際上沒有嘗試過這個; 可能存在輕微的語法錯誤,但邏輯應該是合理的。 請注意,我也完成了零錯誤檢查,因此您可能希望做得更強大。

我能想到的最快速但最丑陋的答案是使用狀態機逐個字符地解析它。 它非常快,但非常具體且相當復雜。 我看到它的方式,你可以有幾種狀態:

  • 解析密鑰
  • 解析價值
  • 准備

例:

int length = foo.length();
int state = READY;
for (int i=0; i<length; ++i) {
   switch (state) {
      case READY:
        //Skip commas and brackets
        //Transition to the KEY state if you find a letter
        break;
      case KEY:
        //Read until you hit a = then transition to the value state
        //append each letter to a StringBuilder and track the name
        //Store the name when you transition to the value state
        break;
      case VALUE:
        //Read until you hit a , then transition to the ready state
        //Remember to save the built-key and built-value somewhere
        break;
   }
}

此外,使用StringTokenizers(快速)或Regexs(速度較慢)可以更快地實現這一點。 但總的來說,個性化解析很可能是最快的方式。

如果字符串有很多條目,你可能最好不用StringTokenizer來手動解析以保存一些內存(如果你必須解析數千個字符串,那么值得額外的代碼):


public static Map parse(String s) {
    HashMap map = new HashMap();
    s = s.substring(1, s.length() - 1).trim(); //get rid of the brackets
    int kpos = 0; //the starting position of the key
    int eqpos = s.indexOf('='); //the position of the key/value separator
    boolean more = eqpos > 0;
    while (more) {
        int cmpos = s.indexOf(',', eqpos + 1); //position of the entry separator
        String key = s.substring(kpos, eqpos).trim();
        if (cmpos > 0) {
            map.put(key, s.substring(eqpos + 1, cmpos).trim());
            eqpos = s.indexOf('=', cmpos + 1);
            more = eqpos > 0;
            if (more) {
                kpos = cmpos + 1;
            }
        } else {
            map.put(key, s.substring(eqpos + 1).trim());
            more = false;
        }
    }
    return map;
}

我用這些字符串測試了這段代碼,它運行正常:

{K1 = V1}

{k1 = v1,k2 = v2,k3 = v3,k4 = v4}

{k1 = v1,}

請找到我的解決方案:

public class KeyValueParser {

    private final String line;
    private final String divToken;
    private final String eqToken;
    private Map<String, String> map = new HashMap<String, String>();

    // user_uid=224620; pass=e10adc3949ba59abbe56e057f20f883e;
    public KeyValueParser(String line, String divToken, String eqToken) {
        this.line = line;
        this.divToken = divToken;
        this.eqToken = eqToken;
        proccess();
    }

    public void proccess() {
        if (Strings.isNullOrEmpty(line) || Strings.isNullOrEmpty(divToken) || Strings.isNullOrEmpty(eqToken)) {
            return;
        }
        for (String div : line.split(divToken)) {
            if (Strings.isNullOrEmpty(div)) {
                continue;
            }
            String[] split = div.split(eqToken);
            if (split.length != 2) {
                continue;
            }
            String key = split[0];
            String value = split[1];
            if (Strings.isNullOrEmpty(key)) {
                continue;
            }
            map.put(key.trim(), value.trim());
        }

    }

    public String getValue(String key) {
        return map.get(key);
    }
}

用法

KeyValueParser line = new KeyValueParser("user_uid=224620; pass=e10adc3949ba59abbe56e057f20f883e;", ";", "=");
String userUID = line.getValue("user_uid")

寫的沒有測試:

String result = null;
int i = foo.indexOf(key+"=");
if (i != -1 && (foo.charAt(i-1) == '{' || foo.charAt(i-1) == ',')) {
    int j = foo.indexOf(',', i);
    if (j == -1) j = foo.length() - 1;
    result = foo.substring(i+key.length()+1, j);
}
return result;

是的,這很難看:-)

好吧,假設值中沒有'='或',',最簡單(和破舊)的方法是:

int start = foo.indexOf(key+'=') + key.length() + 1;
int end =  foo.indexOf(',',i) - 1;
if (end==-1) end = foo.indexOf('}',i) - 1;
return (start<end)?foo.substring(start,end):null;

是的,不推薦:)

添加代碼以檢查fookey存在是留給讀者的練習:-)

String foo = "{k1=v1,k2=v2,...}";

String getValue(String key){
    int offset = foo.indexOf(key+'=') + key.length() + 1;
    return foo.substring(foo.indexOf('=', offset)+1,foo.indexOf(',', offset));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM