简体   繁体   English

查找Java中正则表达式的第一个匹配项的索引

[英]Finding the index of the first match of a regular expression in Java

EDIT: I found the answer here. 编辑:我在这里找到了答案。 Returning the String found with a regular expression 返回用正则表达式找到的字符串

Is there a straightforward way to get a list of all the substrings that match a regex within a string? 是否有一种简单的方法来获取与字符串中的正则表达式匹配的所有子字符串的列表?

It should do something like this. 它应该做这样的事情。

  • Example string: Google 字符串示例: Google
  • Example regex: (og.e) 正则表达式示例: (og.e)
  • What I want to obtain with this method: ogle 我想用这种方法获得什么: ogle

Another example. 另一个例子。

  • Example string: Facebook 示例字符串: Facebook
  • Example regex: (ao) String I want to obtain with this method: acebo 正则表达式示例: (ao)我要使用此方法获取的字符串: acebo

EDIT: I've found something that might be relevant to this question. 编辑:我发现了一些可能与此问题有关的东西。 http://www.java2s.com/Tutorial/CSharp/0360__Regular-Expression/Matchindexandvalue.htm I still don't know whether this will do what I want it to do. http://www.java2s.com/Tutorial/CSharp/0360__Regular-Expression/Matchindexandvalue.htm我仍然不知道这是否会实现我想要的功能。

You need to start learn/use java.util.regex API classes - Pattern and Matcher. 您需要开始学习/使用java.util.regex API类-模式和匹配器。 For more info on regular expression read this tutorial . 有关正则表达式的更多信息,请阅读本教程

Sample: 样品:

 Pattern pat=Pattern.compile("og.e");
 Matcher mat=pat.matcher("Google");
 if(mat.find())
     System.out.println(mat.start());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM