2011-10-28 16 views
146

我准备了一个简单的代码片段,以便将错误的部分与我的Web应用程序分开。Java中的split()方法不适用于点(。)

public class Main { 

    public static void main(String[] args) throws IOException { 
     System.out.print("\nEnter a string:->"); 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String temp = br.readLine(); 

     String words[] = temp.split("."); 

     for (int i = 0; i < words.length; i++) { 
      System.out.println(words[i] + "\n"); 
     } 
    } 
} 

我在构建Web应用程序JSF时测试了它。我只想知道为什么在上面的代码temp.split(".")不起作用。声明

System.out.println(words[i]+"\n"); 

控制台上没有显示任何内容表示它没有经过循环。当我将temp.split()方法的参数更改为其他字符时,它和往常一样正常工作。可能是什么问题?

+3

Escape it。拆分在正则表达式上工作 –

+5

Yikes,它*默认*到Java中的正则表达式? –

回答

352

java.lang.String.split在正则表达式上拆分,.在正则表达式中表示“任何字符”。

尝试temp.split("\\.")

+0

它也适用于我。我在为“|”做事它与“\\ |”一起工作。谢谢 – Bhupinder

2

它工作正常。你读过the documentation吗?该字符串被转换为正则表达式。

.是匹配所有输入字符的特殊字符。

与任何正则表达式特殊字符一样,您使用\进行转义。您需要额外的\用于Java字符串转义。

8

尝试:

String words[]=temp.split("\\."); 

的方法是: “”

String[] split(String regex) 

是正则表达式中的保留字符

52

documentation on split()说:

拆分此字符串周围的给定regular expression匹配。

(重点煤矿。)

的点是在正则表达式语法一个特殊字符。使用Pattern.quote()的参数分裂(),如果你想分割上一些文字字符串模式:

String[] words = temp.split(Pattern.quote(".")); 
+0

它总是更好地使用Pattern.quote –

10

这个方法使用正则表达式,而不是一个字符串,点在正则表达式有特殊意义。像这样逃脱它split("\\.")。你需要一个双反斜杠,第二个逃避第一个。

2
private String temp = "mahesh.hiren.darshan"; 

    String s_temp[] = temp.split("[.]"); 

    Log.e("1", ""+s_temp[0]); 
5

\\.是简单的答案。这里是你的帮助的简单代码。

while (line != null) { 
    //    
    String[] words = line.split("\\."); 
    wr = ""; 
    mean = ""; 
    if (words.length > 2) { 
     wr = words[0] + words[1]; 
     mean = words[2]; 

    } else { 
     wr = words[0]; 
     mean = words[1]; 
    } 
} 
相关问题