Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi. I have a text file. Content of the text file looks something like this

ms:{some text}; gl:{some text}; ms:{some text};
I need to extract the text and group it on the basis of the heading(By heading i mean to say ms, gs). Here is my code
Java
import java.io.BufferedReader;
import java.io.File;

import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class u{
	static int i=0;
	public static void main(String[] args) {
		File file=new File("File location");
		try {
			BufferedReader br =new BufferedReader(new FileReader(file.getAbsoluteFile()));
			String input;
			StringBuilder sb=new StringBuilder();
			while((input=br.readLine())!=null){
				sb.append(input);
			}
			input=sb.toString();
			Pattern pattern=Pattern.compile("(.*?):\\{(.*?)\\};");
			Matcher matcher=pattern.matcher(input);
			//System.out.println(input);
			if(matcher.find()){
				System.out.println("i");
				System.out.println(matcher.group(1));
				/*if(matcher.group(2)!=null){
					System.out.println(matcher.group(2));
				}*/
				//System.out.println(matcher.group(1));
			}
			//System.out.println(i);
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

Regex does not seem to be working. What is the problem with my code?
Posted

1 solution

Your regex look like this - http://www.regexper.com/#(.*%3F)%3A%5C%5C%7B(.*%3F)%5C%5C%7D%3B[^]
I believe this will do better - http://www.regexper.com/#(.%2B%3A)(%5C%7B.%2B%5C%7D)%3B[^]

Also - when you have to check a string for repeating pattern use split to find all the parts...
 
Share this answer
 
v2
Comments
coolRahul_12 26-Feb-14 7:36am    
Iam already using the regex of your first link but without luck.
Kornfeld Eliyahu Peter 26-Feb-14 7:39am    
I know - see what I wrote before. Just added it for visualize it for you...
What about the second regex, I made for you?
coolRahul_12 26-Feb-14 7:39am    
Nope. Not working :(
Kornfeld Eliyahu Peter 26-Feb-14 7:41am    
Can you elaborate on 'not working'?
Kornfeld Eliyahu Peter 26-Feb-14 7:51am    
I think I see it know - you use mathcer, try split instead...

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