简体   繁体   中英

Regex to match number end of file path string

I have the following file names, and looking to extract the number after "_R" :

  • \\FileName_R 10 .txt => 10
  • \\FileName_R_ 10 .txt => 10

I have successfully used the regex:

_R_?(\d+)\.txt$

Now, I'm looking to adapt it to work with the following variation:

  • \\FileName_R 10 _1.txt => 10
  • \\FileName_R_ 10 _1.txt => 10
  • \\FileName_R 10 _11.txt => 10

I tried

_R_?(\d+)_?\d+?\.txt$

which seems to work for the later examples, but breaks with the first ones.

Thanks.

_R_?(\d+)(_\d+)?.txt$

The problem you were having is that \\d+? makes the repetition lazy instead of making it optional. In other words, it was still trying to match at least one digit, just that it was trying to match the least amount (instead of the maximum amount) of digits for there to be a match.


EDIT : To use grouping without introducing a capturing group, you could use (?:) :

_R_?(\d+)(?:_\d+)?.txt$

Edit: missing underscores

由于\\ d不仅限于0-9位数字: https : _R_?([0-9]+)(?:_[0-9]+)?\\.txt$ ,我将使用: _R_?([0-9]+)(?:_[0-9]+)?\\.txt$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM