我正在尝试找到一个可以匹配字符并替换它们的正则表达式,但有条件。虽然我在找到角色方面取得了一些成功,但在替换时我发现了一些问题。
例如: 如果我有一个字符串说“mnh ghty stuff”
所以我将每个字符替换为a=1 b=2 c=3直到y=25
所以它的输出将是“123 4567 891011
”
但是如果我发现第一个字符从字母 K 开始的单词,则不应替换该单词
即对于 ex= abc kdefg hijk 其输出必须是这样的 123 kdefg 891011
任何人都可以告诉我该怎么做吗?
我尝试了下面的代码,但它不起作用。
if(count>0)
{
str = "";
String str123=enter_text.getText().toString().toLowerCase();
Matcher matcher = Pattern.compile("t(\\w+)(\\s)").matcher(enter_text.getText().toString().toLowerCase());
while(matcher.find())
{
str1=matcher.group(1);
System.out.println("k letter "+str1);
}
str=enter_text.getText().toString().toLowerCase(). replace("a","1"). replace("b","2"). replace("c","3"). replace("d","4"). replace("e","5").
}
非常感谢任何帮助。
最佳答案
常见:
final String input = "abc kdefg hijk";
final StringBuilder output = new StringBuilder( 1024 );
第一种方法:
final Pattern pattern = Pattern.compile( "(\\w+)" );
final Matcher matcher = pattern.matcher( input );
while( matcher.find()) {
final String word = matcher.group( 1 );
output.append( ' ' );
if( word.charAt( 0 ) == 'k' ) {
output.append( word );
}
else {
for( int i = 0; i < word.length(); ++i ) {
output.append( 1 + word.charAt( i ) - 'a' );
}
}
}
第二种方法:
final String[] words = input.split( "\\W+" ) ;
for( final String word : words ) {
output.append( ' ' );
if( word.charAt( 0 ) == 'k' ) {
output.append( word );
}
else {
for( int i = 0; i < word.length(); ++i ) {
output.append( 1 + word.charAt( i ) - 'a' );
}
}
}
常见:
System.out.println( output.toString());
两种情况下的输出相同:
123 kdefg 891011
关于java - 正则表达式: Replace a word conditionally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25481435/