Using Delimiter not removing special character
The text file contains the following data. I wish to remove the '$' from each row of the text file. I also wish to store the Name,Drink and Cost in variables for future manipulation. However, that can be performed later. I do not understand what is wrong with my code, Here is the Textfile Data:
Problem solved using Regex escape pattern. I had to replace the "$" with "s*$s*"
Rubin$Vodka$55
Alex$Gin$22
Max$Water$FREE
Code:
File filename = new File("animals2.txt");
try{
Scanner sc = new Scanner(filename);
String line = sc.nextLine();
Scanner linesc = new Scanner(line).useDelimiter("$");
while(linesc.hasNext()){
String name = linesc.next();
txaDisplay.append(name + "n");
}
}
catch(Exception e){
e.printStackTrace();
}
Simply change this line of code:
Scanner linesc = new Scanner(line).useDelimiter("s*$s*");
You need to pass a regular expression pattern escaping the $ sign.
你可以试试这个..
File filename = new File("animals2.txt");
try{
Scanner sc = new Scanner(filename);
while(sc.hasNext())
{
StringBuffer txaDisplay = new StringBuffer();
String line = sc.nextLine();
StringTokenizer linesc = new StringTokenizer(line,"/($)/g");
while(linesc.hasMoreElements()){
String name = linesc.nextToken();
txaDisplay.append(name+" ");
}
System.out.println(txaDisplay);
}
}
catch(Exception e){
e.printStackTrace();
}
Use the split
method of the String
. You cannot accomplish what you are trying with Scanner.
public static void main( String[] args)
{
File filename = new File( "animals2.txt");
try{
Scanner sc = new Scanner( filename);
while( sc.hasNextLine())
{
String line = sc.nextLine();
String[] arr = line.split( "$");
for( String str : arr)
{
txaDisplay.append( str + "n");
}
}
} catch( Exception e) {
e.printStackTrace();
}
}
As a side note, do not use StringTokenizer. Here is what the documentation says:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
链接地址: http://www.djcxy.com/p/78348.html上一篇: Java:解析文件中的行
下一篇: 使用分隔符不删除特殊字符