替换"占位符"资源字符串?

时间:2016-01-15 12:14:56

标签: java android regex

我的问题的背景是我尝试本地化一些HTML文件,但我不希望每种语言都有完整的HTML副本,我只想做它" Android方式",并在我的HTML中使用本地化的字符串资源。

假设我在String中有一些HTML,在将HTML发送到WebView之前应该用字符串资源替换占位符 - 我该怎么做?

假设我有这个HTML:

<string name="myTitle">My title</string>
<string name="myContent">My content</string>

和这些字符串资源:

pairup = $(if $1$2,$(firstword $1):$(firstword $2) $(call pairup,$(wordlist 2,$(words $1),$1),$(wordlist 2,$(words $2),$2)))

现在,举一个例子,这个简单的我可以使用String.replace(),但是如果我想让它更具动态性,即当我不想写任何新的替换代码时该怎么办?在HTML中添加更多占位符?我知道这是可能的,但我无法在线找到任何示例(大多数正则表达式示例都是简单的静态搜索和替换操作)。

1 个答案:

答案 0 :(得分:0)

通过一些反复试验,我设法自己提出这个解决方案,不确定那里是否有更好/更有效的解决方案?

// Read asset file into String
StringBuilder buf = new StringBuilder();
InputStream is = null;
BufferedReader reader = null;

try{
    is = getActivity().getAssets().open("html/index.html");
    reader= new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String line;

    while ((line=reader.readLine()) != null) {
        buf.append(line);
    }
}
catch(IOException e){
    e.printStackTrace();
}
finally{
    try{
        reader.close();
        is.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }

}

String htmlStr = buf.toString();


// Create Regex matcher to match [xxx] where xxx is a string resource name
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher( htmlStr );


// Replace matches with resource strings
while(m.find()) {
    String placeholder = m.group(); // Placeholder including [] -> [xxx]
    String placeholderName = m.group(1); // Placeholder name    -> xxx

    // Find the string resource
    int resId = getResources().getIdentifier(placeholderName, "string", getActivity().getPackageName() );

    // Resource not found?              
    if( resId == 0 )
        continue;

    // Replace the placeholder (including []) with the string resource              
    htmlStr = htmlStr.replace(placeholder, getResources().getString( resId ));

    // Reset the Matcher to search in the new HTML string
    m.reset(htmlStr);           
}


// Load HTML string into WebView
webView.loadData(htmlStr, "text/html", "UTF-8");