我需要从文件中获取一个字符串,在起始字符串和结束字符串之间,但是在返回的字符串中,我需要在起始字符串之前有2行。
例如,下面是我的字符串块,我需要找到以“:25:RO68BTRL04701202281399XX”开头并以“ - }”开头的行,但还要在开始搜索字符串之前返回前两行:< / p>
{1:F01BTRLRO22AXXX1111111111}{2:I940BTRLRO22XXXXN}{3:{108:047MSOG16103001F}}{4: <br />
:20:047RONCRT0028139901<br />
:25:RO68BTRL04701202281399XX<br />
:28C:00697/00001<br />
:60F:C160411RON580868,35<br />
:61:1604110411C537,91NTRFC31EIOP161020001<br />
:86:PLATI CARTELE AP 1351271 CALGIRA FCT.12138114 S I FCT.12145656 CALGIRA TR ANSILVANIA SRL RO81BTRL RO NCRT0278617701 36 BTRL RO2 2 Incasare OP canal ele ctronic<br />
:61:1604110411C279,44NTRF801EIOP161020101
:86:12135020 12144465 AP11309 84 FANTASI STILL SRL FANT ASI STILL SRL RO56BTRL 001 01202N50350XX 16 BTRL RO22 Incasare OP canal elec tronic<br />
:61:1604110411C1149,41NTRF020EIOP161020002<br />
:86:CV F 12143919 12135600 EN IGMA COM SRL RO08BTRL 0200 1202D01120XX 159 BTRL RO22 Incasare OP canal elec tronic<br />
:61:1604110411C53,52NTRF325EIOP161020051<br />
:86: AP1383577 cv fact 1213519 0/ 31.03.20 16 reincarcari electronice GLISSANDO CO STEA SNC RO26BTRL 02501202 121834XX 20 BTRL RO22 Inca sare OP canal electronic<br />
:61:1604110411D695,15NTRF047EPOP161020204<br />
:86:PLATA PP F 2479 PRAM CADE S SRL 7227 BTRL RO22 Plata OP intra canal electronic<br />
:61:1604110411C223,01NTRF010EIOP161020085<br />
:86: AP 1353368 F 12134396 121 40760 COM TURISM MARKET S RL Comturism Market SRL C OMTURISM MARKET SRL RO21B TRL01001202M68296XX 94 BT RLRO22 Incasare OP cana l electronic<br />
:62F:C160411RON1162675,04 <br />
:64:C160411RON1162675,04 <br />
-}
我在java中的代码是这样的(正在运行,只是它没有返回我想要的东西,意思是startString减去2行和endString之间的字符串):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class bt {
public static void main(String[] args) {
// TODO code application logic here
File fileName = new File("bta.txt");
try {
String startToken = ":25:RO68BTRL04701202281399XX";
String endToken = "-}";
boolean output = false;
int nrLinie=0;
Scanner scan = new Scanner(fileName);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (output==false && line.indexOf(startToken) > -1) {
output = true;
//line = line.substring(line.indexOf(startToken)+startToken.length());
line = line.substring(line.indexOf(startToken)+1,line.indexOf(endToken)+endToken.length());
} else if (output && line.indexOf(endToken) > -1) {
//output = false;
//System.out.println(line.substring(0, line.indexOf(endToken)));
}
if (output) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
谢谢你,因为任何帮助都非常感激。
答案 0 :(得分:0)
这个正则表达式可以做到。请参阅regex101 for demo。
((?:[^\r\n]*\r?\n){2}):25:RO68BTRL04701202281399XX(.*?)-\}