所以,我试图在RegEx 模式中使用一个参数,我找不到一个模式,因为参数是一个简单的字符串,它包含在更大的字符串中。以下是我从这个codingbat.com上获取的任务本身,所以一切都要清楚:
任务的前提和解释。
给定一个字符串和一个非空字符串,返回一个版本 原始字符串,其中所有字符都被加号(“+”)替换, 除了保留的单词字符串的外观 不变。
我的代码:
public String plusOut(String str, String word) {
if(str.matches(".*(<word>.*<word>){1,}.*") || str.matches(".*(<word>.*<word>.*<word>){1,}.*")) {
return str.replaceAll(".", "+"); //after finding the argument I can easily exclude it but for now I have a bigger problem in the if-condition
} else {
return str;
}
}
Java中是否有方法匹配参数?上述代码由于显而易见的原因(<word>
)不起作用。如何在字符串RegEx?
word
更新
这是我得到的最接近但它仅适用于 word String的最后一个字符。
public String plusOut(String str, String word)
{
if(str.matches(".*("+ word + ".*" + word + "){1,}.*") || str.matches(".*(" + word + ".*" + word + ".*" + word + "){1,}.*") || str.matches(".*("+ word + "){1,}.*"))
{
return str.replaceAll(".(?<!" + word + ")", "+");
} else {
return str;
}
}
输入/输出
plusOut(“12xy34”,“xy”)→“+++ y ++”(预期“++ xy ++”)
plusOut(“12xy34”,“1”)→“1 +++++”(预期“1 +++++”)
plusOut(“12xy34xyabcxy”,“xy”)→“+++ y +++ y ++++ y”(预期“++ xy ++ xy +++ xy”)
这是因为RegEx中的?。
答案 0 :(得分:0)
您需要使用Java的+
运算符
if(str.matches("<"+word+">")){ // Now word will be replaced by the value
//do Anything
}
答案 1 :(得分:0)
您不能在正则表达式模式中放置参数。您可以通过将变量与正则表达式模式部分连接来创建正则表达式对象,如下所示:
public String plusOut(String str, String word)
{
if(str.matches(".*("+ word + ".*" + word + "){1,}.*") || str.matches(".*(" + word + ".*" + word + ".*" + word + "){1,}.*"))
{
return str.replaceAll(".", "+");
}
else
{
return str;
}
}
答案 2 :(得分:0)
你不能只使用模式来做,你必须编写除模式之外的一些代码。试试这个:
public static String plusOut(String input, String word) {
StringBuilder builder = new StringBuilder();
Pattern pattern = Pattern.compile(Pattern.quote(word));
Matcher matcher = pattern.matcher(input);
int start = 0;
while(matcher.find()) {
char[] replacement = new char[matcher.start() - start];
Arrays.fill(replacement, '+');
builder.append(new String(replacement)).append(word);
start = matcher.end();
}
if(start < input.length()) {
char[] replacement = new char[input.length() - start];
Arrays.fill(replacement, '+');
builder.append(new String(replacement));
}
return builder.toString();
}