0

I am using this simple code:

if (data.matches("(\\d+)\\D+"))
   data = "$1";

I want to find a string that begins with a number and then have non-number string. I need to extract the number itself. The backreference doesn't work. I am getting that data equals literally $1 instead of the matched expression. What am I doing wrong?

Renjith
  • 5,783
  • 9
  • 31
  • 42
AJ Gottes
  • 401
  • 1
  • 3
  • 15
  • read from a file: 0 and endless of unreadable characters... and I only want the number. – AJ Gottes Jul 12 '13 at 10:03
  • 1
    Well, you can't use back-references like that. If you want to access matched data outside the pattern, you need to use Pattern and Matcher classes. – Rohit Jain Jul 12 '13 at 10:05
  • @Rohit thanks! Can you write a code example that will be the same as I want? – AJ Gottes Jul 12 '13 at 10:07
  • 1
    Go through [this tutorial](http://docs.oracle.com/javase/tutorial/essential/regex/matcher.html) and [this too](http://www.vogella.com/articles/JavaRegularExpressions/article.html) and [this](http://www.tutorialspoint.com/java/java_regular_expressions.htm) – Rohit Jain Jul 12 '13 at 10:10
  • Have a look at [this example](http://www.vogella.com/articles/JavaRegularExpressions/article.html#regexjava). `matcher.group(1)` will have your number. – Martin Ender Jul 12 '13 at 10:10

0 Answers0