java
iphone
css
c
xml
ajax
linux
regex
mysql
silverlight
flash
html5
algorithm
facebook
cocoa
php5
asp
jsp
postgresql
dom
For the input that you provided :
String text = "Lots of text..." + "\n" + "String=Value" + "\n" + "PackageName=com.company.package" + "\n" + "String=Value";
The code that YOU wrote:
Pattern pattern = Pattern.compile("PackageName=(.*)"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { String packageName = matcher.group(1); System.out.println(packageName); }
Works fine, it does retrieve the package name.
Unless you have anything to add that will clarify the problem, and what is wrong, then this is not even a question, everything works. :)
Cheers, Eugene.
I think your problem might be in the String lines at the top. You cannot declare a String literal over multiple lines in Java, you need to separate them by \n characters:
String
\n
String text = "Lots of text...\nString=Value\nPackageName=com.company.package\nString=Value";
To make it more readable, you can do this:
String text = "Lots of text...\n" + "String=Value\n" + "PackageName=com.company.package\n" + "String=Value";
Once that change is made, the code you provide works fine for me on JDK6.
That said, here is the regex slightly improved:
Pattern pattern = Pattern.compile("PackageName\\s*=\\s*(.*)"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { String packageName = matcher.group(1); }
The only change I made was to add \\s*: this means any whitespace (or none) so you can put PackageName = abc and have it work (note that the regex item itself is actually \s* but you have to escape the \ character in Java).
\\s*
PackageName = abc
\s*
\
My java code
String text = "Lots of text... String=Value PackageName=com.company.package String=Value"; Pattern pattern = Pattern.compile("PackageName=(.*)"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { String packageName = matcher.group(1); System.out.println(packageName); }
The result runs :
com.company.package String=Value