您将如何使用正则表达式编写函数来执行以下操作:
- 将小写字母“a”替换为大写字母,反之亦然
- 如果容易扩展,对所有字母都这样做
- 其中单词由空格和
>
分隔和<
是某些词的特殊标记,替换>word
与word<
反之亦然。- 如果有帮助,您可以限制输入,以便所有单词都必须以一种或另一种方式标记。
- 将后增量 (
i++;
) 替换为前增量 (++i;
),反之亦然。变量名称是[a-z]+
.现在可以假定输入仅限于这些语句中的一堆。奖励:也做递减。
也对其他风格的解决方案感兴趣。
注意:这不是家庭作业问题。另请参阅我之前对正则表达式的探索:
- > Regex split into overlapping strings (Alan Moore 的回答特别有启发性)
- > Can you use zero-width matching regex in String split? (我的解决方案利用了一个已知的 Java 正则表达式错误,关于非显而易见的长度回顾!)
最佳答案
您无疑已经明白,做这种事情的唯一明智的方法是一次性完成所有替换,根据匹配的内容动态生成替换字符串。
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/