java - 正则表达式拆分字符串

标签 java regex split

我有这个打印的代码:

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

我尝试在 [#] 拆分,但没有成功。

我应该在 split 中输入什么,以便我只能得到 # 之后的部分:你好,再见

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);

最佳答案

如果我理解正确,您只想通过正则表达式从输入字符串中提取“Hello”和“Bye”。

在这种情况下,我只会对 # 之间的任何内容进行迭代匹配和 > ,因此:

// 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

关于java - 正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18855209/

相关文章:

c - 通过添加 0 来分割 c 字符串(段错误)

python - 使用空格分隔符和最大长度拆分字符串

java - 复制构造函数是否需要复制互斥体?

java - 当服务器在触发事件时发送电子邮件时,是否有必要在 HttpServlet 中使用serialVersionUID

javascript - 正则表达式通过选择在 li 中创建级别

Javascript RegEx - 分割 Html 字符串

java - 查找所有单行循环和 If 并添加括号

java - 将curl命令翻译成java/android

Java程序监控其他Java程序

python re.compile 并用 ÆØÅ 字符分割