my file is here
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));
}
i cannot handle exception.If i dont have any 3rd occurence of [ ] parentheses i am getting stringindexoutofbound exception else i am getting null pointer exception
Why are you doing that complex starts with etc as value inside [] can change. Why don't you try this?
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.