Jatin
Jatin

Reputation: 31754

Get String in between either single quotes or empty space

I wish to have a regular expression which gives me the name of classLoader inserted in single quotes/empty-space but not a mixture of both. i.e. some examples. :

2014-05-21 22:05:13.685 TRACE [Core] sun.misc.Launcher$AppClassLoader@62c8aeb3 searching for resource 'java/util/LoggerFactory.class'.

expected output sun.misc.Launcher$AppClassLoader@62c8aeb3

2014-05-21 22:05:13.685 TRACE [Core] Class 'org.jboss.weld.metadata.TypeStore' not found in classloader 'org.jboss.modules.ModuleClassLoader@4ebded0b'.

expected output org.jboss.modules.ModuleClassLoader@4ebded0b

2014-05-21 22:04:34.591 INFO [Core] Started plugin org.zeroturnaround.javarebel.integration.IntegrationPlugin from /Users/endragor/Downloads/jrebel/jrebel.jar in sun.misc.Launcher$AppClassLoader@62c8aeb3

expected output sun.misc.Launcher$AppClassLoader@62c8aeb3

Note that for last exampe, the line ends with new line character. i.e. there is nothing in front.

This is what I have tried ".*[\\s|'](.*ClassLoader.*[^']*)['|\\s].*". But it doesn't work. For the first example it gives below rather than sun.misc.Launcher$AppClassLoader@62c8aeb3:

sun.misc.Launcher$AppClassLoader@62c8aeb3 searching for resource 'java/util/LoggerFactory.class

Also my regex does not handle if the class loader string is end of the line i.e. example-3 above. What can I do so that either ' is considered or \\s but not both

Upvotes: 3

Views: 189

Answers (3)

Braj
Braj

Reputation: 46891

As operator has changed the original post so here is the updated answer.

Simply use below pattern to check for default toString() representation of Object class.

[\w\.$]+ClassLoader@[a-z0-9]+

Pattern Expiation:

\w      A word character: [a-zA-Z_0-9]
X+      X, one or more times

[abc]   a, b, or c (simple class)

Snapshot:

enter image description here

Here is the DEMO

Upvotes: 1

Mifmif
Mifmif

Reputation: 3190

Try this one :

String extractedValue=yourString.replaceAll("(.*)([ '])(.*ClassLoader.*?)(\\2)(.*)", "$3");

Whenever we want to extract String between a predifined set of value , where the first and last delimiter should have the same value , we can use Backreference feature .

Upvotes: 2

Kent
Kent

Reputation: 195289

this regex should do without grouping:

[^\s']*ClassLoader[^\s']*

in java it should be:

[^\\s']*ClassLoader[^\\s']*

you don't need the pipe | in [..], in regex [abcd] means a or b or c or d

update

add java codes:

public static void main(String[] args){
        Pattern p = Pattern.compile("[^\\s']*ClassLoader[^\\s']*");
        Matcher m = p.matcher("2014-05-21 22:05:13.685 TRACE [Core] sun.misc.Launcher$AppClassLoader@62c8aeb3 searching for resource 'java/util/LoggerFactory.class'.");
        if (m.find()) {
            System.out.println(m.group());
        }
    }

output:

sun.misc.Launcher$AppClassLoader@62c8aeb3

Upvotes: 1

Related Questions