如何实现“替代”在java中

发布于 2024-10-05 21:49:05 字数 349 浏览 3 评论 0原文

“supplant() 对字符串进行变量替换。它会扫描字符串,查找包含在 { } 大括号中的表达式。如果找到表达式,则将其用作对象上的键,并且如果该键具有字符串值或数字值,它被替换为括号表达式并重复。”

更具体地说,我正在尝试做一些类似的事情:

public static String supplant(CharSequence message, Map<String,Object> params)

我正在尝试使用像 \{([\w]*)\} 这样的正则表达式来捕获变量,然后查找地图并替换,但我无法编写正则表达式匹配...

你如何在java中实现supplant()?

"supplant() does variable substitution on the string. It scans through the string looking for expressions enclosed in { } braces. If an expression is found, use it as a key on the object, and if the key has a string value or number value, it is substituted for the bracket expression and it repeats."

More specifically, i am trying to do somethink like:

public static String supplant(CharSequence message, Map<String,Object> params)

I am trying to use a regex like \{([\w]*)\} to capture the variables and then lookup the map and replace, but i couldn't write a regex that matches...

How would you implement supplant() in java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

却一份温柔 2024-10-12 21:49:05

它需要使用这种确切的格式吗? Java 已经具有将变量替换为字符串的内置方法。

请参阅:

Does it need to work with this exact format? Java already has built-in methods for substituting variables into strings.

See:

各空 2024-10-12 21:49:05

您所描述的内容通常称为“模板化”。有许多模板应用程序和库,但如果您只是想要一个快速而肮脏的解决方案,则可以使用正则表达式轻松实现。

在许多正则表达式风格中,您将使用内置的callbackcallout机制,例如PHP的preg_replace_callback函数或Perl的/e< /code> 和 /ee 修饰符。 Java没有类似的东西,但它提供了API让你自己实现它。下面是一个示例:

import java.util.*;
import java.util.regex.*;

public class Test
{
  public static void main(String[] args) throws Exception
  {
    String s = "Lorem ipsum {foo} impedit civibus ei pri, legimus\n" +
        "antiopam no {marco}, quo id everti forensibus maiestatis.";
    Map<String,Object> p = new HashMap<String,Object>()
    {{
      put("foo", "BAR");
      put("marco", "POLO!");
    }};
    System.out.printf("%s%n%n%s%n", s, supplant(s, p));
  }

  public static CharSequence supplant(CharSequence message, Map<String,Object> params)
  {
    Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher(message);
    StringBuffer sb = new StringBuffer();
    while (m.find())
    {
      m.appendReplacement(sb, "");
      String key = m.group(1);
      sb.append(params.get(key).toString());
    }
    m.appendTail(sb);
    return sb.toString();
  }
}

显然,此代码遗漏了一些基本组件(主要是异常处理),但它演示了此技术的要点:

  1. 使用括号捕获大括号内的内容,然后通过调用 group(1)< 来访问它/code> 在匹配器上。
  2. 使用 appendReplacement(sb, "") 附加上一个匹配项(如果有)和当前匹配项之间出现的任何文本。
  3. 查找替换并使用 StringBuffer 的 append() 方法追加它。 (您可以通过将替换字符串作为第二个参数传递给appendReplacement()来合并步骤2和3,但是随后您必须注意美元符号和反斜杠字符串,接受特殊处理。这种方式要简单得多。)
  4. 使用 appendTail(sb) 附加最后一次匹配后剩下的内容。

有几个人已经发布了帮助程序类,可以让您完成此类任务,而无需编写所有样板代码。我最喜欢的是 Elliott Hughes 的 重写器

What you describe is more commonly called templating. There are many templating applications and libraries out there, but if you just want a quick-and-dirty solution, it can easily be implemented with regexes.

In many regex flavors you would use a built-in callback or callout mechanism, like PHP's preg_replace_callback function, or Perl's /e and /ee modifiers. Java doesn't have anything like that, but it provides the API to let you implement it yourself. Here's an example:

import java.util.*;
import java.util.regex.*;

public class Test
{
  public static void main(String[] args) throws Exception
  {
    String s = "Lorem ipsum {foo} impedit civibus ei pri, legimus\n" +
        "antiopam no {marco}, quo id everti forensibus maiestatis.";
    Map<String,Object> p = new HashMap<String,Object>()
    {{
      put("foo", "BAR");
      put("marco", "POLO!");
    }};
    System.out.printf("%s%n%n%s%n", s, supplant(s, p));
  }

  public static CharSequence supplant(CharSequence message, Map<String,Object> params)
  {
    Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher(message);
    StringBuffer sb = new StringBuffer();
    while (m.find())
    {
      m.appendReplacement(sb, "");
      String key = m.group(1);
      sb.append(params.get(key).toString());
    }
    m.appendTail(sb);
    return sb.toString();
  }
}

Obviously this code leaves out some essential components (principally exception handling), but it demonstrates the main points of this technique:

  1. Capture the content within the braces using parentheses, then access it by calling group(1) on the Matcher.
  2. Use appendReplacement(sb, "") to append whatever text appeared between the previous match (if there was one) and the current one.
  3. Look up the replacement and append it using StringBuffer's append() method. (You could combine steps 2 and 3 by passing the replacement string as the second argument to appendReplacement(), but then you would have to watch out for dollar signs and backslashes in the string, which receive special treatment. This way is much simpler.)
  4. Use appendTail(sb) to append whatever's left after the last match.

Several people have published helper classes that let you accomplish this sort of task without having to write all that boilerplate code. My favorite is Elliott Hughes's Rewriter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文