Click here to Skip to main content
15,917,456 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi all
I have an input which looks something like 192.168.90.8 - - [321/Jan/2013:00:00:11 -0800]xyz.
I need to extract ip and date. My code is

Java
public class c {
public static void main(String[] args) throws IOException {
	
	input="192.168.90.8 - - [321/Jan/2013:00:00:11 -0800]";
	//System.out.println(input);
	Pattern pattern=Pattern.compile("((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d]) - -([\\d]+/[\\w]+/[\\d]+:[\\d]+:[\\d]+:[\\d]+)");
	Matcher matcher=pattern.matcher(input);
	while(matcher.find()){
		System.out.println("found");
		System.out.println(matcher.group(3));
		
	}
}
}
Iam unable to find issue with my regex
Posted

1 solution

If you want to extract IP and date, why don't you create two patterns?
String input="192.168.90.8 - - [321/Jan/2013:00:00:11 -0800]";
		//System.out.println(input);
		Pattern pattern=Pattern.compile("((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))");
		Matcher matcher=pattern.matcher(input);
		if (matcher.find()){
			System.out.println("found");
			System.out.println(matcher.group());
			
		}
		
		pattern=Pattern.compile("([\\d]+/[\\w]+/[\\d]+:[\\d]+:[\\d]+:[\\d]+)");
		matcher=pattern.matcher(input);
		if (matcher.find()){
			System.out.println("found");
			System.out.println(matcher.group());	
		}

Output:
found
192.168.90.8
found
321/Jan/2013:00:00:11
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900