Java 使用正则表达式替换字符串结尾
我试图将一个单词/字符串的结尾与以下表达式匹配:“m[abcd]”,并将此结尾替换为另一个类似于“?q”的结尾,其中问号与字符a、b、c或d中的一个匹配。问题是,我有很多不同的结局。这是一个例子: 结束:m[abcd] 再植:?q 关键词:dfma、ghmc、tdfmd 期望结果:dfaq、ghcq、tdfdqJava 使用正则表达式替换字符串结尾,java,regex,matching,Java,Regex,Matching,我试图将一个单词/字符串的结尾与以下表达式匹配:“m[abcd]”,并将此结尾替换为另一个类似于“?q”的结尾,其中问号与字符a、b、c或d中的一个匹配。问题是,我有很多不同的结局。这是一个例子: 结束:m[abcd] 再植:?q 关键词:dfma、ghmc、tdfmd 期望结果:dfaq、ghcq、tdfdq 如何在Java或任何其他Java方法中使用字符串的replaceAll方法?也许我可以用很多代码来实现,但我要求的是一个更短的解决方案。我不知道如何连接到Separet正则表达式。假设您
如何在Java或任何其他Java方法中使用字符串的replaceAll方法?也许我可以用很多代码来实现,但我要求的是一个更短的解决方案。我不知道如何连接到Separet正则表达式。假设您的字符串包含整个单词:
String resultString = subjectString.replaceAll(
"(?x) # Multiline regex:\n" +
"m # Match a literal m\n" +
"( # Match and capture in backreference no. 1\n" +
" [a-d] # One letter from the range a through d\n" +
") # End of capturing group\n" +
"$ # Assert position at the end of the string", \
"$1q"); // replace with the contents of group no. 1 + q
如果您的字符串包含许多单词,并且您希望一次查找/替换所有单词,则根据stema的建议使用
\\b
而不是$
(但仅在搜索正则表达式中;替换部分需要保留为“$1q”
)。假设您的字符串包含整个单词:
String resultString = subjectString.replaceAll(
"(?x) # Multiline regex:\n" +
"m # Match a literal m\n" +
"( # Match and capture in backreference no. 1\n" +
" [a-d] # One letter from the range a through d\n" +
") # End of capturing group\n" +
"$ # Assert position at the end of the string", \
"$1q"); // replace with the contents of group no. 1 + q
如果您的字符串包含许多单词,并且您希望一次查找/替换所有单词,则根据stema的建议使用
\\b
而不是$
(但仅在搜索正则表达式中;替换部分需要保留为“$1q”
)。您可以使用捕获组来完成此操作。例如
String pattern = "m([abcd])\\b"; //notice the parantheses around [abcd].
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher("dfma");
String str = matcher.replaceAll("$1q"); //$1 represent the captured group
System.out.println(str);
matcher = regex.matcher("ghmc");
str = matcher.replaceAll("$1q");
System.out.println(str);
matcher = regex.matcher("tdfmd");
str = matcher.replaceAll("$1q");
System.out.println(str);
您可以使用捕获组来执行此操作。例如
String pattern = "m([abcd])\\b"; //notice the parantheses around [abcd].
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher("dfma");
String str = matcher.replaceAll("$1q"); //$1 represent the captured group
System.out.println(str);
matcher = regex.matcher("ghmc");
str = matcher.replaceAll("$1q");
System.out.println(str);
matcher = regex.matcher("tdfmd");
str = matcher.replaceAll("$1q");
System.out.println(str);
+你太快了。。。但是由于他要求“在单词/字符串的末尾”
\b
可能是比$
+1更好的选择,你太快了。。。但是,由于他要求“在单词/字符串的末尾”\b
可能是比$
更好的选择,因此您在结尾缺少了一个锚。此正则表达式将在单词中的任何位置找到m[abcd]。您在末尾缺少一个锚。这个正则表达式将在单词的任何地方找到m[abcd]。