Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index of the first match of a regular expression in Java

Tags:

java

regex

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
  • Example regex: (og.e)
  • What I want to obtain with this method: ogle

Another example.

  • Example string: Facebook
  • Example regex: (a.o) String I want to obtain with this method: 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.

like image 667
Anderson Green Avatar asked Dec 29 '25 01:12

Anderson Green


1 Answers

You need to start learn/use java.util.regex API classes - Pattern and Matcher. 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());
like image 106
KV Prajapati Avatar answered Dec 31 '25 14:12

KV Prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!