Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)
I have several strings in the rough form:

[some text] [some number] [some more text]

I want to extract the text in [some number] using the Java Regex classes.

I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].

I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].

1 Answer

0 votes
by (46k points)

Try:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Regex1 {

    public static void main(String[]args) {

        Pattern p = Pattern.compile("\\d+");

        Matcher m = p.matcher("hello1234goodboy789very2345");

        while(m.find()) {

            System.out.println(m.group());

        }

    }

}

Output:

1234

789

2345

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 22, 2021 in Java by dante07 (13.1k points)
0 votes
4 answers
0 votes
1 answer

Browse Categories

...