[英]Extracting a certain part of string in Java using regex
I need to extract a certain part of string in Java using regex. 我需要使用正则表达式在Java中提取字符串的特定部分。
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
. 例如,我有一个字符串completei4e10
,我需要提取i
和e
之间的值-在这种情况下,结果将是4
: completei 4 e10
。
How can I do this? 我怎样才能做到这一点?
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
. 或者,模式可能是[^i]*i([^e]*)e.*
,具体取决于i
和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. 像[aeiou]
这样的东西与任何一个小写元音相匹配。 [^…]
is a negated character class. [^…]
是一个否定的字符类。 [^aeiou]
matches one of anything but the lowercase vowels. [^aeiou]
匹配除小写元音之外的任何内容 。
The (…)
is a capturing group . (…)
是一个捕获组 。 The *
and +
are repetition specifier in this context. 在这种情况下, *
和+
是重复说明符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.