简体   繁体   中英

Why does this regex [^\/]\d{4} not match a 4 digit number at the begining of a line?

The pattern [^\\/]\\d{4} works for 2014(i) and 01/01/2015 but not 2014(i) when it is the first item in the text file.

Sample in regexstorm

You are looking for a character before digits and at the beginning of line / string there is no character right before them. As @JonSkeet mentioned in comments since no character before digits is found at beginning of a line, [^\\/] consumes first digit so number of left digits doesn't match \\d{4} . That said, you are looking for this:

(?<!\/)\d{4}
  • (?<!\\/) a negative lookbehind which assures no / before digits (an assertion, no character consuming applies)

Live demo

or if you have no problem with matching preceding character:

(?:^|[^\/])\d{4}

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