日期:2014-05-20  浏览次数:20760 次

请问如何用正则处理这样的字符串
大家好:
如何用正则按需求处理以下字符串呢!


@article{AcharyaBI93,
author = "Acharya, A. and Badrinath, B.R. and Imielinski, T.",
title = "Impact of Mobility on Distributed Computations",
journal = OSR,
volume = 27,
number = 2,
pages = "15-20",
month = "April",
year = 1993
}

找出“article”和“=”前所有关键字,并把引号变成花括号,关键字变为大写,最后结果为:

@Article{AcharyaBI93,
AUTHOR = {Acharya, A. and Badrinath, B. R. and Imielinski, T.},
TITLE = {Impact of Mobility on Distributed Computations},
JOURNAL = {Operating Systems Review},
VOLUME = 27,
NUMBER = 2,
PAGES = {15--20},
MONTH = {April},
YEAR = 1993
}


谢谢各位,不胜感激


------解决方案--------------------
话说
Acharya, A. and Badrinath, B. R. and Imielinski, T. --> Acharya, A. and Badrinath, B.R. and Imielinski, T.
OSR --> Operating Systems Review
15-20 --> 15--20
是怎么回事
------解决方案--------------------
忘了key变大写了

Java code

//String separator = System.getProperty("line.separator"); 
String separator = "\n"; //不知道LZ是否按行分割的,
                             //如果不是按行分割,用separator="",也能对应,就是结果只有1行

String s = "@article{AcharyaBI93," + "\n" +
"author = \"Acharya, A. and Badrinath, B.R. and Imielinski, T.\"," + separator + 
"title = \"Impact of Mobility on Distributed Computations\"," + separator +
"journal = OSR," + separator +
"volume = 27," + separator +
"number = 2," + separator +
"pages = \"15-20\"," + separator +
"month = \"April\"," + separator +
"year = 1993" + separator +
"}";

System.out.println("----------original----------");
System.out.println(s);


s = s.replaceAll("^@article(.*)", "@Article$1").replaceAll("\"(.*?)\"", "{$1}");
StringBuffer buf = new StringBuffer();
Pattern p = Pattern.compile("((?<=("+separator+"[}],|,|))[^,]*?)(\\s*=\\s*.*?("+separator+"|[}],|,))");
Matcher m = p.matcher(s);
while (m.find()) {
    String s1 = m.group(1);
    System.out.println(m.group(1));
    m.appendReplacement(buf, m.group(1).toUpperCase()+"$3");
}
m.appendTail(buf);

System.out.println("----------after replace----------");
System.out.println(buf);