hello, i need to extract an certain part from an string using java
ie i have a string completei4e10
i need to extract the value which is inside i
and e
- i.e. "4" completei 4 e10
using regex....
hello, i need to extract an certain part from an string using java
ie i have a string completei4e10
i need to extract the value which is inside i
and e
- i.e. "4" completei 4 e10
using regex....
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 ) );
}
}
}
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.
The pattern would look like this: .+i([0-9])+e.+
So this outputs 4
:
String str = "completei4e10";
Pattern p = Pattern.compile(".+i([0-9])+e.+");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
}