Java 替换“;占位符;使用资源字符串?

Java 替换“;占位符;使用资源字符串?,java,android,regex,Java,Android,Regex,我的问题的背景是,我正在尝试本地化一些HTML文件,但我不希望每种语言都有完整的HTML副本,我只想用“Android方式”,并在我的HTML中使用本地化的字符串资源 假设我在一个字符串中有一些HTML,在将HTML发送到WebView之前,应该用字符串资源替换占位符——我该怎么做 例如,假设我有以下HTML: <div>[myTitle]</div> <div>[myContent]</div> [myTitle] [内容] 这些字符串资源:

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

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

例如,假设我有以下HTML:

<div>[myTitle]</div>
<div>[myContent]</div>
[myTitle]
[内容]
这些字符串资源:

<string name="myTitle">My title</string>
<string name="myContent">My content</string>
我的标题
我的内容

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

通过一些尝试和错误,我自己设法想出了这个解决方案,不确定是否有更好/更有效的解决方案

// 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");

为什么要使用HTML来达到这个目的?您可以使用XML或json,可以轻松解析。因为它是HTML,所以我将它发送到WebView…您可以用HTML的方式来完成。第一步将唯一标识符与占位符一起放置,例如{{}包装键。第二步:为字符串资源创建一个静态Hashmap,key作为字符串名称,value作为其所需值。不适用于作为字符串的html。使用[\n\s]拆分该html内容,然后迭代字符串数组。现在找到唯一的占位符包装器,如{{然后从占位符中提取密钥并替换字符串资源数组中的内容。这可能不是我想要的-我希望能够用字符串资源替换HTML中的任何占位符。如果我正确阅读了您的建议,每次添加新占位符时,我都必须编辑该静态哈希映射在我的HTML中?不管怎样,现在有了一个有效的解决方案,请参见下文。