• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RegEx - contains numbers but no letters

 
Jerry Lee
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried for an hour and could figure it out. I could find a way around, but I'd like to know the answer.

I am reading a file and would like to remove lines as follows:
00:02:21,365 --> 00:02:24,027

So, please give a Java regular expression that will pick up a line that contains numbers, but it doesn't contain any letters. Therefore:

1) 00:02:21,365 --> 00:02:24,027 (Yes)
2) (an empty line) (No - because it doesn't have numbers)
3) whatever123 (No - because it has letters)

Thanks.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12022
25
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can you show us some of the things you've tried?
 
Jerry Lee
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried this one it doesn't work.
[0-9&&[^a-zA-Z]]

After reading this page, I know why it doesn't work now:
http://java.sun.com/docs/books/tutorial/essential/regex/char_classes.html

Regular Expression Test Page:
http://www.fileformat.info/tool/regex.htm
 
Campbell Ritchie
Sheriff
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you found the escape sequences which match digits? You should find them in the Java Tutorial link you posted. I think you want something like \d, but in a String literal you have to escape the \ like this "\\d".
 
Alan Moore
Ranch Hand
Posts: 262
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jerry Lee:
I tried this one it doesn't work.
[0-9&&[^a-zA-Z]]

That regex matches one character that is a digit and isn't a letter. You need a regex that matches a whole line, and you need to do the two tests separately. One regex for a line of characters other than letters would be ...and for a line that contains a digit, You don't need to call matches() twice though, because you can state one of the requirements as a lookahead: Finally, if you use the matches() method, you don't need the '^' and '$' anchors at either end of the regex, but you do need the '$' in the lookahead, to make sure it checks the whole line.

By the way, here's a site with a better regex tutorial:

http://www.regular-expressions.info/
[ May 28, 2008: Message edited by: Alan Moore ]
 
Jerry Lee
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for the detailed info. This is really helpful.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic