Reputation: 65
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?
Upvotes: 0
Views: 1641
Reputation: 383726
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.
Upvotes: 0
Reputation: 68942
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 ) );
}
}
}
Upvotes: 3