java - 用于循环替换的正则表达式

标签 java regex string replace

您将如何使用正则表达式编写函数来执行以下操作:

  1. 将小写字母“a”替换为大写字母,反之亦然
    • 如果容易扩展,对所有字母都这样做
  2. 其中单词由空格和 > 分隔和 <是某些词的特殊标记,替换>wordword<反之亦然。
    • 如果有帮助,您可以限制输入,以便所有单词都必须以一种或另一种方式标记。
  3. 将后增量 ( i++; ) 替换为前增量 ( ++i; ),反之亦然。变量名称是 [a-z]+ .现在可以假定输入仅限于这些语句中的一堆。奖励:也做递减。

也对其他风格的解决方案感兴趣。


注意:这不是家庭作业问题。另请参阅我之前对正则表达式的探索:

最佳答案

您无疑已经明白,做这种事情的唯一明智的方法是一次性完成所有替换,根据匹配的内容动态生成替换字符串。

Java 在当今的主要语言中似乎是独一无二的,因为它没有提供一种方便的方法来做到这一点,但它可以做到。您只需使用 Matcher 类提供的较低级别的 API。这是基于 Elliott Hughes 的权威 Rewriter 的演示。类:

import java.util.regex.*;

/**
 * A Rewriter does a global substitution in the strings passed to its
 * 'rewrite' method. It uses the pattern supplied to its constructor, and is
 * like 'String.replaceAll' except for the fact that its replacement strings
 * are generated by invoking a method you write, rather than from another
 * string. This class is supposed to be equivalent to Ruby's 'gsub' when
 * given a block. This is the nicest syntax I've managed to come up with in
 * Java so far. It's not too bad, and might actually be preferable if you
 * want to do the same rewriting to a number of strings in the same method
 * or class. See the example 'main' for a sample of how to use this class.
 *
 * @author Elliott Hughes
 */
public abstract class Rewriter
{
  private Pattern pattern;
  private Matcher matcher;

  /**
   * Constructs a rewriter using the given regular expression; the syntax is
   * the same as for 'Pattern.compile'.
   */
  public Rewriter(String regex)
  {
    this.pattern = Pattern.compile(regex);
  }

  /**
   * Returns the input subsequence captured by the given group during the
   * previous match operation.
   */
  public String group(int i)
  {
    return matcher.group(i);
  }

  /**
   * Overridden to compute a replacement for each match. Use the method
   * 'group' to access the captured groups.
   */
  public abstract String replacement();

  /**
   * Returns the result of rewriting 'original' by invoking the method
   * 'replacement' for each match of the regular expression supplied to the
   * constructor.
   */
  public String rewrite(CharSequence original)
  {
    this.matcher = pattern.matcher(original);
    StringBuffer result = new StringBuffer(original.length());
    while (matcher.find())
    {
      matcher.appendReplacement(result, "");
      result.append(replacement());
    }
    matcher.appendTail(result);
    return result.toString();
  }



  public static void main(String... args) throws Exception
  {
    String str = ">Foo baR<";

    // anonymous subclass example:
    Rewriter caseSwapper = new Rewriter("[A-Za-z]")
    {
      public String replacement()
      {
        char ch0 = group(0).charAt(0);
        char ch1 = Character.isUpperCase(ch0) ?
                   Character.toLowerCase(ch0) :
                   Character.toUpperCase(ch0);
        return String.valueOf(ch1);
      }
    };
    System.out.println(caseSwapper.rewrite(str));

    // inline subclass example:
    System.out.println(new Rewriter(">(\\w+)|(\\w+)<")
    {
      public String replacement()
      {
        return group(1) != null ? group(1) + "<"
                                : ">" + group(2);
      }
    }.rewrite(str));

  }
}

关于java - 用于循环替换的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2445589/

相关文章:

Java - 正则表达式,分别替换

c++ - std::string::erase 导致内存损坏

python - 如何在python中获取文本字符串的视觉长度

java - 将随机数转换为 XY 坐标以进行绘图

c - 正则表达式不正确 c

python - 用于查找星号的正则表达式(仅当不被数字包围时)

java - 字符串和数组混合语法以及非常罕见的用法

java - 无法从 Spring 应用程序连接到 mssql 服务器

java - 使用 JdbcPooledConnectionSource 时检查连接的成本

使用数组的 Java 矩阵