java - 正则表达式: Replace a word conditionally

标签 java regex

我正在尝试找到一个可以匹配字符并替换它们的正则表达式,但有条件。虽然我在找到角色方面取得了一些成功,但在替换时我发现了一些问题。

例如: 如果我有一个字符串说“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().toLowerCas‌​e()); 
    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/

相关文章:

java - 突破碰撞检测

java - 将自定义协议(protocol)导入 MS Excel/Access

java - Java Session 的低级实现

java - 使用转义解析单引号之间的大字符串

c++ - perl 正则表达式比 c++/boost 更快

regex - Matlab 中的正则表达式仅保留数组中的指定项

java - 如何以编程方式获取 Camera RAW 元数据信息 Android

java - 使用 AspectJ 注释获取方法输入的属性

python - 替换一行中第一个单词中匹配正则表达式的所有匹配项

regex - 从 Varnish 中获取 url 值