Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of a pattern in a string using regex

Tags:

java

string

regex

I want to search a string for a specific pattern.

Do the regular expression classes provide the positions (indexes within the string) of the pattern within the string?
There can be more that 1 occurences of the pattern.
Any practical example?

like image 872
Cratylus Avatar asked Jan 20 '12 08:01

Cratylus


People also ask

What does this mean in regex \\ s *?

\\s*,\\s* It says zero or more occurrence of whitespace characters, followed by a comma and then followed by zero or more occurrence of whitespace characters. These are called short hand expressions. You can find similar regex in this site: http://www.regular-expressions.info/shorthand.html.

How do I extract a pattern in Java?

Solution: Use the Java Pattern and Matcher classes, supply a regular expression (regex) to the Pattern class, use the find method of the Matcher class to see if there is a match, then use the group method to extract the actual group of characters from the String that matches your regular expression.

How do I find an integer from a string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.

What is regex pattern in Java?

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern.


2 Answers

Use Matcher:

public static void printMatches(String text, String regex) {     Pattern pattern = Pattern.compile(regex);     Matcher matcher = pattern.matcher(text);     // Check all occurrences     while (matcher.find()) {         System.out.print("Start index: " + matcher.start());         System.out.print(" End index: " + matcher.end());         System.out.println(" Found: " + matcher.group());     } } 
like image 52
Jean Logeart Avatar answered Sep 29 '22 12:09

Jean Logeart


special edition answer from Jean Logeart

public static int[] regExIndex(String pattern, String text, Integer fromIndex){     Matcher matcher = Pattern.compile(pattern).matcher(text);     if ( ( fromIndex != null && matcher.find(fromIndex) ) || matcher.find()) {         return new int[]{matcher.start(), matcher.end()};     }     return new int[]{-1, -1}; } 
like image 24
Ar maj Avatar answered Sep 29 '22 13:09

Ar maj