Search code examples
androidregexfilenames

Regular Expression failed when I try to get all files that name only contains number


I try to list all the files under "/proc" on my android device,and get all those files' names only contain numbers,such as '123','435'.I try to filter those by regular expression.I tried three expressions below but all of these failed sometimes:

^[0-9]+$
 [0-9]+
  \d+

I wonder how can the three expressions can match such as "14971" but can't match "15003"?


Solution

  • I think boober Bunz is right, that the file extension is the difference. All three of your expressions match both "14971" and "15003"

    the best way is to pull the extensions off the fileNames, and then use the most restrictive expression you need to: ^[0-9]+$

    or if you want to just leave the extension on, this would most likely work for you:

    "^[0-9]+[.][^.]*$"

    start of string, one or more digits, must have a . and then any number of non . end of string. this would not match:

    "123.123.txt"