java - 使用从文本文件中删除所有数字和字母数字字符

标签 java regex string replaceall

我有 2 个文本文件:

文件1 - 此文件的格式为user_id tweet_id tweet_text

文件 1

60730027    6298443824  thank you echo park. you've changed A LOT, but as long as I'm getting paid to make you move, I'm still with it! 2009-12-03 02:54:10
60730027    6297282530  fat Albert Einstein goin in right now over here!!!  2009-12-03 01:35:22

文件2
该文件的格式为genome_id name ascii_name

4045417 Southwest Indent    Southwest Indent
4045418 Southeast Point     Southeast Point     

下面是读取文件1的代码片段:

public void readfromFile() throws FileNotFoundException {
    Scanner inputStream;
    String source=null;
     FileInputStream file = new FileInputStream("file1.txt");   
        String regex = "/[a-zA-Z ]+/";
        Scanner fileScan = new Scanner(file); 

        while(fileScan.hasNextLine()){
            word = fileScan.nextLine();
            word = word.replaceAll(regex, "").toLowerCase();
            PrintWriter outputStreamName = new PrintWriter(new FileOutputStream("temp.txt"));
            outputStreamName.printf("%s",word);
}

我的目的首先是用空值替换 user_id、tweet_id、genome_id 中存在的数据。然后将大写值转换为小写值。但是,现在每当此代码处理 file1 时,文本文件都不会发生任何变化。我也想知道发生了什么事。当我将其输出到控制台时,我得到了输出。

预期输出:

thank you echo park youve changed a lot but as long as im getting paid to make you move im still with it

fat albert einstein goin in right now over here

最佳答案

根据预期输出,您想要替换除字母、点和单词之间的空格之外的所有内容。

[^a-zA-Z. ]+|(?<=\d)\s*(?=\d)|(?<=\D)\s*(?=\d)|(?<=\d)\s*(?=\D)

这里是online demo

或者尝试不使用 Lookaround

[^a-zA-Z. ]+|\d\s+\d|\D\s+\d|\d\s+\D

此处 \s 匹配任何空白字符 [\r\n\t\f ]

示例代码:

String regex = "[^a-zA-Z. ]+|(?<=\\d)\\s*(?=\\d)|(?<=\\D)\\s*(?=\\d)|(?<=\\d)\\s*(?=\\D)";
str.replaceAll(regex,"");

输出:

thank you echo park. youve changed A LOT but as long as Im getting paid to make you move Im still with it
fat Albert Einstein goin in right now over here
<小时/>

要从输出中排除 ',请使用 [^a-zA-Z.'。 ]+ 否则 Imyouve 更改为 Imyouve

更好使用[a-zA-Z']+仅获取所有单词。这是demo

示例代码:

String str = "60730027    6297282530  fat Albert Einstein goin in right now over here!!!  2009-12-03 01:35:22 ";
Pattern p = Pattern.compile("[a-zA-Z']+");
Matcher m = p.matcher(str);
while (m.find()) {
    System.out.print(m.group()+" ");
}

输出:

fat Albert Einstein goin in right now over here 
<小时/>

注意:您正在检查下一行,因此

更改:

source = inputStream.next();

致:

source = inputStream.nextLine();

关于java - 使用从文本文件中删除所有数字和字母数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337621/

相关文章:

python - 从文件读取并写入 StringIO - Python

string - (Delphi)如何读取字符串变量并将其分成多行并放入列表框中

java - 记录 actionListener 的最佳实践

java - TreeViewer 中的同一个 child 、不同的 parent

php - .htaccess 子目录中语言检测规则

java - 正则表达式验证 csv 字符串

c# - 如何正则表达式用方法结果替换匹配组项

c++ - 如何获取 std::string 中的字符数?

java - 错误 - trustAnchors 参数必须非空

java - Android主 Activity 的元素在按下子 Activity 的后退按钮后没有响应