Temple
Temple

Reputation: 1631

Regex match single word

Waht is the java regex to match only "pkgName" from string:

"name=pkgname -path=some.apk -minutes=120"

I have tried:

public static final Pattern PKG_NAME_REGEX = Pattern.compile("(name=)(\\b.+\\b)\\s");

buit group 2 of Match gives me: "pkgname -path=some.apk -minutes=120"

thanks

Upvotes: 1

Views: 1109

Answers (3)

Gurwinder Singh
Gurwinder Singh

Reputation: 39457

Try this:

    String s = "name=pkgname -path=some.apk -minutes=120";
    Pattern p = Pattern.compile("name=(\\w+)");
    Matcher m = p.matcher(s);
    if (m.find())
        System.out.println(m.group(1));

Upvotes: 2

anubhava
anubhava

Reputation: 784958

What is the java regex to match only "pkgName" from string:

You can use a positive lookbehind:

(?<=name=)\S+
  • (?<=name=) is positive look-behind to assert that previous position has name=
  • \S+ will match 1 or more non-space characters

Using Java:

public static final Pattern PKG_NAME_REGEX = Pattern.compile("(?<=name=)\\S+");

RegEx Demo

Upvotes: 3

Toto
Toto

Reputation: 91375

Repace the dot by word character:

"(name=)(\\b\\w+\\b)\\s"

and the word boundaries are not usfull here:

"(name=)(\\w+)\\s"

Upvotes: 0

Related Questions