我有一个这样的字符串:"你好$ namevar $你好吗?"。我想:
1)我使用以下代码:
String my = "hi $namevar$ how are you?";
Matcher m = Pattern.compile("\\$(\\w.*?)\\$").matcher(my);
while (m.find()) {
System.out.println(m.group(1));
}
2)和3)的任何提示?
答案 0 :(得分:8)
这是一种更通用的方法,它不要求您提供模式,适用于多个占位符,并且可以匹配多个单词的占位符。比如说,我们有以下模板和输入字符串:
String input = "Hi John Doe, how are you? I'm Jane.";
String template = "Hi $namevar$, how are you? I'm $namevar2$.";
因此,我们首先解析所有占位符名称并将其添加到Map
。我们使用Map
,以便我们稍后可以将实际的String
值指定为键。
Matcher m = Pattern.compile("\\$(\\w*?)\\$").matcher(template);
Map<String, String> vars = new LinkedHashMap<String, String>();
while (m.find()) {
System.out.println(m.group(1));
vars.put(m.group(1), null);
}
现在,我们生成模式以将占位符值解析为
String pattern = template;
// escape regex special characters
pattern = pattern.replaceAll("([?.])", "\\\\$1");
for (String var : vars.keySet()) {
// replace placeholders with capture groups
pattern = pattern.replaceAll("\\$"+var+"\\$", "([\\\\w\\\\s]+?)");
}
现在,我们进行匹配并捕获占位符值。然后将这些值存储在上面创建的同一Map
中,并将其分配给相应的占位符变量。
m = Pattern.compile(pattern).matcher(input);
if (m.matches()) {
int i = 0;
for (String var : vars.keySet()) {
vars.put(var, m.group(++i));
}
}
现在,让我们通过迭代Map
来打印出我们捕获的值
for (Map.Entry<String, String> entry : vars.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
输出:
namevar = John Doe
namevar2 = Jane
答案 1 :(得分:1)
尝试类似:
String mydata = "hi john how are you?";
System.out.println(mydata.matches("hi (.*?) how are you\\?"));//requirement 2
Pattern pattern = Pattern.compile("hi (.*?) how are you?");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find()) {
System.out.println(matcher.group(1));//requirement 3
}
Output:
true
john