[英]Extracting a certain part of string in Java using regex
我需要使用正則表達式在Java中提取字符串的特定部分。
例如,我有一個字符串completei4e10
,我需要提取i
和e
之間的值-在這種情況下,結果將是4
: completei 4 e10
。
我怎樣才能做到這一點?
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 ) );
}
}
}
有幾種方法可以執行此操作,但是您可以執行以下操作:
String str = "completei4e10";
str = str.replaceAll("completei(\\d+)e.*", "$1");
System.out.println(str); // 4
或者,模式可能是[^i]*i([^e]*)e.*
,具體取決於i
和e
周圍的內容。
System.out.println(
"here comes the i%@#$%@$#e there you go i000e"
.replaceAll("[^i]*i([^e]*)e.*", "$1")
);
// %@#$%@$#
[…]
是一個字符類 。 像[aeiou]
這樣的東西與任何一個小寫元音相匹配。 [^…]
是一個否定的字符類。 [^aeiou]
匹配除小寫元音之外的任何內容 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.