【发布时间】:2013-05-05 13:01:25
【问题描述】:
我有以下字符串:
您在哪里 [员工姓名]? 你有 [Shift] 班次...
以及包含以下内容的字符串列表:
1.员工姓名
2. 换档
我需要在长字符串的列表中找到给定的字符串,并将它们替换为另一个内容(包括[ 和] 字符)。
因此,例如第一个字符串需要更改为:
Jhon Green 你在哪里? 你有早班...
有什么简单的方法吗?使用 IndexOf 会给我这个字符串的位置,但是我如何包含 [ , ] 字符呢?
更新: 这是我目前测试的代码:
Scanner sc = new Scanner(smsText);
for (String s; (s = sc.findWithinHorizon("(?<=\\[).*?(?=\\])", 0)) != null;)
{
words.add(s);
}
for (int j = 0; j < words.size(); j++)
{
Log.d(TAG, "The value for column: "+words.get(j) +" is: "+ rowData.getValue(words.get(j)));
smsText.replaceFirst("\\[" + words.get(j) + "\\]", rowData.getValue(words.get(j)));
}
Log.d(TAG, "Final String is: "+ smsText);
这没有给我正确的结果,字符串没有被替换。
更新 2: 对我有用的解决方案是:
Scanner sc = new Scanner(smsText);
for (String s; (s = sc.findWithinHorizon("(?<=\\[).*?(?=\\])", 0)) != null;)
{
columnNames.add(s);
}
for (int j = 0; j < columnNames.size(); j++)
{
Log.d(TAG, "The value for column: "+columnNames.get(j) +" is: "+ rowData.getValue(columnNames.get(j)));
smsText = smsText.replaceFirst("\\[" + columnNames.get(j) + "\\]", rowData.getValue(columnNames.get(j)));
}
Log.d(TAG, "Final String is: "+ smsText);
感谢大家的帮助。
【问题讨论】:
-
如果您可以控制模板,请将其切换为
%s并使用String.format()。 -
@CommonsWare,不幸的是我没有,“[”和“]”里面的短语是一个列名,我需要从中提取替换的内容,所以它不能被改变要么。
-
@EmilAdz 这个字符串
Where Are You [Employee Name]? your have a [Shift] shift常见吗?你想用员工的名字替换[Employee Name]吗?告诉我 -
整个字符串以及员工姓名字符串都是动态的,可以从服务器端更改。
-
你需要从 replaceFirst 中保存你的结果:
smsText = smsText.replaceFirst(...
标签: java android string indexof