0

I need to extract a certain part of string in Java using regex.

For example, I have a string completei4e10, and I need to extract the value that is between the i and e - in this case, the result would be 4: completei 4 e10.

How can I do this?

2 Answers 2

3
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile( "^[a-zA-Z]+([0-9]+).*" );
        Matcher m = p.matcher( "completei4e10" );

        if ( m.find() ) {
            System.out.println( m.group( 1 ) );
        }

    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the method I always use.
0

There are several ways to do this, but you can do:

    String str = "completei4e10";

    str = str.replaceAll("completei(\\d+)e.*", "$1");

    System.out.println(str); // 4

Or maybe the pattern is [^i]*i([^e]*)e.*, depending on what can be around the i and e.

    System.out.println(
        "here comes the i%@#$%@$#e there you go i000e"
            .replaceAll("[^i]*i([^e]*)e.*", "$1")
    );
    // %@#$%@$#

The […] is a character class. Something like [aeiou] matches one of any of the lowercase vowels. [^…] is a negated character class. [^aeiou] matches one of anything but the lowercase vowels.

The (…) is a capturing group. The * and + are repetition specifier in this context.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.