其实,我试图读取包含多行的文件。为此,我正在使用scanner.nextline()Java阅读线,直到followstop
但是,我想读直到跟随停留点(点分隔符),其后通常跟着空格或结束行字符。
在这种情况下,任何机构可以帮助我吗?
其实,我试图读取包含多行的文件。为此,我正在使用scanner.nextline()Java阅读线,直到followstop
但是,我想读直到跟随停留点(点分隔符),其后通常跟着空格或结束行字符。
在这种情况下,任何机构可以帮助我吗?
使用read()方法并通过char读取char。如果你与之相匹配。这是你的换行符。
其他解决方案可能是设置换行符,然后使用readline()。如果你想搜索,直到一段时间,你可以使用一个Pattern
一个Matcher
我没有试过这种howeever
或读取文件中的ANS使用一次string.split方法
FileReader fin = new FileReader("yourfile.txt");
Scanner src = new Scanner(fin);
// Set delimiters to full stop
src.useDelimiter(".");
while (src.hasNext()) {
// do what you want here
}
我试图使用这种方法,但如果我有(。)后面是其他任何东西例如23.5它会认为该点是一个行分隔符。 –
为了运行你发给我的东西,我会尽我所能,我会看到会发生什么....非常感谢你 –
所以你为什么不尝试在“。”之后加一个空格。所以它变成了“。”像这样:src.useDelimeter(“。”); – Andromeda
。
//Pattern p = Pattern.compile("[^\\.]*\\.(\\s+)");
Pattern p = Pattern.compile(".*?\\.(\\s+)"); //Anything any amount of times,
//followed by a dot and then some whitespace.
Matcher matcher = p.matcher("firstword. secondword.\n");
while(matcher.find()){
boolean space = matcher.group(1).charAt(0) == ' ';
System.out.println(matcher.start() + matcher.group() + "and is space: " + (space ? "TRUE" : "FALSE"));
}
.*?
- .
将匹配任何东西。 *
匹配0次或多次。 ?
是lazy匹配器。它匹配任何类型的任意数量的字符,但它会在第一个句点和空格之前停止(因为懒惰的操作符)。\\.
- 这与一段时间相匹配。在Java中,你必须在正则表达式中加倍转义特殊字符。(\\s+)
- 这意味着匹配空格(\s
,其中包括新行)一次或多次。它匹配一个或多个空白字符。括号“捕获”了正则表达式的这部分内容,以便每次在正则表达式中找到匹配项时,都可以问它在括号内匹配了哪些特定部分。这可以让你知道它是空格还是换行符。matcher.group()
获取刚匹配的字符串。
我在问号中添加了注释,并将其他模式注释掉了,因为它听起来像你可能在某些数据中间有一段时间。问号做“懒惰”匹配。默认情况下,匹配是贪婪的,并将采用最长的匹配字符串。因此,如果字符串中有多个地方的句号后跟一个空格,则它将作为一个匹配返回所有这些内容。一旦达到第一个时间段和空间,懒惰迫使它停止匹配任何字符(。*)。
谢谢你的回复....实际上我不明白这种模式,如果我想读取点(空格或换行符char) –
好吧。我会在那里解决它。我为空白添加了\ s。 –
谢谢我会尝试,我会看到发生了什么....但如何处理新行字符(\ n)和空白在一起 –
试试这个,
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null)
{
if (line.contains(". ") || line.trim().endsWith("."))
{
int length = line.indexOf(". "); // get the index when the line contains dot and space in the middle
stringBuilder.append(line.trim().endsWith(".") ? line
: line.substring(0, length).replace(". ", "." + System.getProperty("line.separator"))); // when the line contains dot at the end or the line may contain the dot with space
System.out.println("stringBuilder : " + stringBuilder.toString());
stringBuilder.delete(0, stringBuilder.toString().length());
if (length != 0)
{
stringBuilder.append(line.substring(length+2, line.length()));
}
}
else
{
stringBuilder.append(line.replace(System.getProperty("line.separator"), " "));
}
}
System.out.println("stringBuilder : "+stringBuilder.toString()); // when the last line not end with dot or not contain dot and space
你有什么tryed?给我们的代码,然后它easyer帮你 –