简体   繁体   中英

How to use extract substring using regex

I am new to java regex. I need to extract "com.mycomp.war.tasks.JmxMetricsTask" from the below line. How can i do with regex?

String test = "id=         com.mycomp.war.tasks.JmxMetricsTask      I run/id-geLh3hM1-1_2 [Svc--DAG]";

Is it too complicated? Is it possible by regex? I need to extract above line in return?

VG

You need to define your problem and requirements more thoroughly.

For the example you show, there is a much simpler solution:

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];

Disclaimer: this might not work as intended for all of your possible inputs. This is why I say that you need to completely define your situation. If all of your inputs match the assumptions I made based on your one example, then this would work without using regular expressions.

There is no need for Regex. You can do it like

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));

But can you explain your actual requirements?? using above, you can get the required string part

Well, you could search for a similar question.;

regexp to match java package name

I modified the regex from the top answer to suit your case. I replace the ^…$ (line start/end) portion with \\b (word boundaries).

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
        }
    }
}

Here's a live example using Regex 101: /\\b[az][a-z0-9_]*(\\.[a-z0-9_]+)+[0-9a-z_]\\b/ig

https://regex101.com/r/RwJtLK/2


You could also just split by whitespace characters and grab the second token.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM