正则表达式分裂字符串 [英] Regex to split string

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

问题描述

我有这个代码打印:

[( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Hello> ), ( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Bye> )]

我试图在[#]拆分,但它没有用。

I tried to split at [#] but it didnt work.

我应该分成什么以便我可以得到#之后的部分:Hello,Bye

What should i put in split so that I can get as a result the part after # only: Hello, Bye

Query query = QueryFactory.create(queryString);
                     QueryExecution qe= QueryExecutionFactory.create(query, model);
                    ResultSet resultset = qe.execSelect();
                    ResultSet results = ResultSetFactory.copyResults(resultset); 
                    final ResultSet results2 = ResultSetFactory.copyResults(results);


                    System.out.println( "== Available Options ==" );
                    ResultSetFormatter.out(System.out, results, query);



    Scanner input = new Scanner(System.in);
    final String inputs;
    inputs = input.next();
    final String[] indices = inputs.split("\\s*,\\s*");

    final List<QuerySolution> selectedSolutions = new ArrayList<QuerySolution>(
            indices.length) {
        {
            final List<QuerySolution> solutions = ResultSetFormatter
                    .toList(results2);
            for (final String index : indices) {
                add(solutions.get(Integer.valueOf(index)));
            }
        }
    };

    System.out.println(selectedSolutions);


推荐答案

如果我理解正确,你只想提取从你的输入字符串到正则表达式你好和再见。

If I understand correctly, you only want to extract "Hello" and "Bye" from your input String through regex.

在这种情况下,我只会使用之间的迭代匹配> ,因此:

In which case, I would just use iterative matching of whatever's in between # and >, as such:

// To clarify, this String is just an example
// Use yourScannerInstance.nextLine to get the real data
String input = "[( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Hello> ), "
                + "( ?Random = <http://www.semanticweb.org/vassilis/ontologies/2013/5/Test#Bye> )]";
// Pattern improved by Brian
// was: #(.+?)>
Pattern p = Pattern.compile("#([^>]+)>");
Matcher m = p.matcher(input);
// To clarify, printing the String out is just for testing purpose
// Add "m.group(1)" to a Collection<String> to use it in further code
while (m.find()) {
    System.out.println(m.group(1));
}

输出:

Hello
Bye

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

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