[英]How to use extract substring using regex
我是Java regex的新手。 我需要從下面的行中提取“ com.mycomp.war.tasks.JmxMetricsTask”。 我該如何使用正則表達式?
String test = "id= com.mycomp.war.tasks.JmxMetricsTask I run/id-geLh3hM1-1_2 [Svc--DAG]";
太復雜了嗎? 正則表達式可能嗎? 我需要提取上面的行作為回報嗎?
VG
您需要更徹底地定義您的問題和要求。
對於您顯示的示例,有一個簡單得多的解決方案:
String test = "id= com.mycomp.war.tasks.JmxMetricsTask I run/id-geLh3hM1-1_2 [Svc--DAG]";
String answer = test.substring(3).trim().split(" ", 2)[0];
免責聲明:這可能不適用於您所有可能的輸入。 這就是為什么我說您需要完全定義您的情況。 如果所有輸入都符合我根據您的一個示例所做的假設,則無需使用正則表達式就可以工作。
不需要正則表達式。 你可以像
String test = "id= com.mycomp.war.tasks.JmxMetricsTask I run/id-geLh3hM1-1_2 [Svc--DAG]";
String subTest = "com.mycomp.war.tasks.JmxMetricsTask";
test.substring(test.indexOf(subTest), subTest.length() + test.indexOf(subTest));
但是您能解釋一下您的實際需求嗎? 在上面使用,您可以獲得所需的字符串部分
好吧,您可以搜索類似的問題。
我從最上面的答案修改了正則表達式以適合您的情況。 我用\\b
(單詞邊界)替換^…$
(行的開始/結束)部分。
import java.util.regex.*;
public class RegexTest {
public static final String PACKAGE_PATTERN = "\\b[a-z][a-z0-9_]*(\\.[a-z0-9_]+)+[0-9a-z_]\\b";
public static void main(String[] args) {
String s = "id= com.mycomp.war.tasks.JmxMetricsTask I run/id-geLh3hM1-1_2 [Svc--DAG]";
Pattern p = Pattern.compile(PACKAGE_PATTERN, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group()); // com.mycomp.war.tasks.JmxMetricsTask
}
}
}
這是一個使用Regex 101的實時示例:/ /\\b[az][a-z0-9_]*(\\.[a-z0-9_]+)+[0-9a-z_]\\b/ig
您也可以按空格字符分開並獲取第二個標記。
public class RegexTest {
public static void main(String[] args) {
String s = "id= com.mycomp.war.tasks.JmxMetricsTask I run/id-geLh3hM1-1_2 [Svc--DAG]";
String[] tokens = s.split("\\s+");
System.out.println(tokens[1]); // com.mycomp.war.tasks
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.