java正则表达式的问题 [英] Issue with the java regex

查看:64
本文介绍了java正则表达式的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我有一个文本文件。文本文件的内容看起来像这样



ms:{some text}; gl:{some text}; ms:{some text};

我需要提取文本并根据标题对其进行分组(按标题我的意思是说ms,gs)。这是我的代码

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

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?

推荐答案

你的正则表达式是这样的 - http://www.regexper.com/#(。*%3F)%3A%5C%5C %7B(。*%3F)%5C%5C%7D%3B [ ^ ]

我相信这会做得更好 - < a href =http://www.regexper.com/#(.%2B%3A)(%5C%7B.%2B%5C%7D)%3B> http://www.regexper.com/# (。%2B%3A)(%5C%7B。%2B%5C%7D)%3B [ ^ ]



另外 - 当您必须检查字符串以重复模式时,使用split来查找所有部分......
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...


这篇关于java正则表达式的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆