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/

相关文章:

regex - 限制 XML 模式中的单词列表

regex - 用于备份服务器上传文件夹的 Bash 脚本

java - 调试(设置断点)评估部分的Ilog Jrules

java - EXcel 表 POI 验证 : Out Of Memory Error

c# regex : get all uri's, 但不是来自特定域

Java 正则表达式,除\r 和\n 之外的所有 ASCII

regex - 使用正则表达式删除除匹配字符串之外的所有文本

java - 与私有(private)构造函数混淆

java - 在调用函数的所有地方删除函数第一个参数的快捷方式

java - 有没有办法在运行时刷新Java应用程序的DNS服务器详细信息?