[英]I have text from textview, I want to erase/delete some data before an empty line
[英]I have some text [text1] [number2] [text3] in a line.I want to extract only the [text3] portion.My Code is working fine.But i cannot handle
我的文件在这里
private static final String FILENAME = "rea/data.txt"; //my file path
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
sCurrentLine = br.readLine();
String lastline="";
String firstLine=br.readLine();
if ( (firstLine.contains("[INFO]") && (firstLine.contains("[OHS_Batch_Restart_utils.sh]")) || (firstLine.contains("[DEBUG]")) && (firstLine.contains("[AppRestart.sh]")) || (firstLine.contains("[INFO]")) && (firstLine.contains("[AppRestart.sh]")) )) // to check lines condition
{
int firstpos= StringUtils.ordinalIndexOf(firstLine, "[", 3); // getting 3rd occurence of parentheses
int secondpos= StringUtils.ordinalIndexOf(firstLine, "]", 3); // getting 3rd occurence of parentheses
System.out.println(firstLine.substring(firstpos,secondpos+1)); //printing value between the 3rd occurence of parentheses
}while ((sCurrentLine = br.readLine()) != null ){
lastline=sCurrentLine; //fixing lst line as currentline
}
if ( (lastline.startsWith("[INFO]") && (lastline.contains("[OHS_Batch_Restart_utils.sh]")) || (lastline.startsWith("[DEBUG]")) && (lastline.contains("[AppRestart.sh]")) || (lastline.startsWith("[INFO]")) && (lastline.contains("[AppRestart.sh]")))) //same condition**strong text**
{
int firstpos= StringUtils.ordinalIndexOf(lastline, "[", 3); // getting 3rd occurence of parentheses
int secondpos= StringUtils.ordinalIndexOf(lastline, "]", 3); // getting 3rd occurence of parentheses
System.out.println(lastline.substring(firstpos,secondpos+1));
}
我无法处理异常。如果我没有第 3 次出现 [] 括号,我将收到 stringindexoutofbound 异常,否则我收到空指针异常
你为什么要以 etc 开头,因为 [] 中的值可能会改变。 你为什么不试试这个?
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class FindThirdMatchInSquareBracketUtil{
public static void main(String[] args) {
String s = "[text1] [number2] [text3]";
String s2 = "[text1] [number2] ";
System.out.println(getThirdMatch(s));
System.out.println(getThirdMatch(s2));
}
private static String getThirdMatch(String s) {
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(s);
int counter = 1;
while (m.find()) {
if (counter == 3) {
return m.group(1);
}
counter++;
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.