[英]Regular Expression to Replace All But One Character In String
I need regular expression to replace all matching characters except the first one in a squence in string. 我需要正则表达式来替换除字符串中的第一个字符之外的所有匹配字符。
For example; 例如;
For matching with 'A' and replacing with 'B' 用于与'A'匹配并用'B'替换
'AAA' should be replaced with 'ABB' “AAA”应替换为“ABB”
'AAA AAA' should be replaced with 'ABB ABB' “AAA AAA”应替换为“ABB ABB”
For matching with ' ' and replacing with 'X' 用于与''匹配并替换为'X'
You need to use this regex for replacement: 您需要使用此正则表达式进行替换:
\\BA
\\B
(between word characters) assert position where \\b
(word boundary) doesn't match \\B
(单词字符之间)断言\\b
(字边界)不匹配的位置 A
matches the character A
literally A
字符匹配A
字面上 Java Code: Java代码:
String repl = input.replaceAll("\\BA", "B");
UPDATE For second part of your question use this regex for replacement: 更新对于问题的第二部分,请使用此正则表达式进行替换:
"(?<!^|\\w) "
Code: 码:
String repl = input.replaceAll("(?<!^|\\w) ", "X");
Negative Lookbehind and Beginning of String Anchor 负面观察和弦锚的开始
Use the regex (?<!^| )A
like this: 使用正则表达式
(?<!^| )A
如下:
String resultString = subjectString.replaceAll("(?<!^| )A", "B");
In the demo , inspect the substitutions at the bottom. 在演示中 ,检查底部的替换。
Explanation 说明
(?<!^| )
asserts that what immediately precedes the position is neither the beginning of the string nor a space character (?<!^| )
断言紧接在该位置之前的内容既不是字符串的开头也不是空格字符 A
matches A
A
匹配A
Reference 参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.