用新行符号分割字符串 [英] Split string by new line symbol

查看:161
本文介绍了用新行符号分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在此文件中拆分行 eng-pol.txt 用换行符号"\ n"替换,它根本无法正常工作...我已经尝试过:

I'm trying to split lines in this file eng-pol.txt by new line symbol "\n" and it's simply not working... I've tried:

String[] words = strLine.split("\n");
System.out.println(Arrays.toString(words));
[abbot    abbot [ˈæbət] <N>\n opat]

String[] words = strLine.split("\\n");
System.out.println(Arrays.toString(words));
[abbot    abbot [ˈæbət] <N>\n opat]

String[] words = strLine.split("\\r|\r");
System.out.println(Arrays.toString(words));
[abbot    abbot [ˈæbət] <N>\n opat]

即使这样:

String[] words = strLine.split(System.getProperty("line.separator"));
System.out.println(Arrays.toString(words));
[abbot    abbot [ˈæbət] <N>\n opat]

我正在使用BufferedReaderreadLine方法读取文件.

I'm reading the file using BufferedReader and readLine method.

推荐答案

我不确定我是否理解正确,但是我发现您的文件包含\n文字(不是实际的换行符).如果要拆分它们,则需要将拆分写为

I'm not sure if I understand you correctly but I see that your file contains \n literals (not actual line breaks). If you want to split on them then you need to write split as

split("\\\\n")

表示\文字的

Regex看起来像\\(需要转义,否则单个\将被视为例如代表数字的\d之类的预定义字符类的开始).

Regex which represents \ literal looks like \\ (it needs to be escaped, otherwise single \ will be treated for example as start of predefined character class like \d which represents digits).

但是表示正则表达式\\的字符串需要写为"\\\\",因为在字符串\中也很特殊,也需要转义.

But String which will represents such regex \\ need to be written as "\\\\" because in string \ is also special and it also needs to be escaped.

简而言之,要使\与正则表达式匹配,您需要分两个级别对其进行转义:

In short to match \ with regex you need to escape it in two levels:

  • 在正则表达式\\
  • 在字符串"\\\\"中.
  • in regex \\
  • in String "\\\\".

这篇关于用新行符号分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆