2014-09-10 49 views
0
/* Look for phone numbers starting with a 0 after a space 
character and replace the 0 with "+44 (0)" */ 

    import java.util.regex.*; 

    public class Reg6 { 

     public static void main (String [] args) { 

      String variable1 = "test"; 
      Pattern phone = Pattern.compile("\\s0"); 
      Matcher action = phone.matcher(args[0]); 
      String worldwide = action.replaceAll(" +44 (0) "); 
      System.out.println(worldwide); 

     } 
    } 

如何将variable1放置到replaceAll方法中?如果将会有一个字符串{$ variable_1},我希望将其替换为我的变量_1,那可能吗?Java将变量替换为匹配

其在PHP模板一样

“{$测试}” - 我想使用的字符串相匹配的名称,并找到匹配这个字符串变量,并把它放在那里通过这个变量值替换所有

它就像模板

+1

你的问题不是很清楚全球 – 2014-09-10 15:13:01

+0

字符串= action.replaceAll(变量1); – MGorgon 2014-09-10 15:15:10

+0

尽管replaceAll()需要正则表达式作为输入 – Lucas 2014-09-10 15:16:15

回答

0

您不必使用模式匹配或者只是 尝试以下

String number ="028346"; 
    if(number.startsWith("0")) 
     System.out.println("+44 (0)" + number.substring(1)); 
0

也许你想这样的:

Pattern varMatch = Pattern.compile("\\{\\$variable_1\\}"); 
Matcher action = varMatch.matcher(worldwide); 
worldwide = action.replaceAll(variable1); 
System.out.println(worldwide);