Need a regex to exclude certain strings

后端 未结 6 1419
无人及你
无人及你 2021-01-02 15:18

I\'m trying to get a regex that will match:

somefile_1.txt
somefile_2.txt
somefile_{anything}.txt

but not match:

somefile_1         


        
6条回答
  •  鱼传尺愫
    2021-01-02 15:45

    The best solution has already been mentioned:

    somefile_(?!16\.txt$).*\.txt
    

    This works, and is greedy enough to take anything coming at it on the same line. If you know, however, that you want a valid file name, I'd suggest also limiting invalid characters:

    somefile_(?!16)[^?%*:|"<>]*\.txt
    

    If you're working with a regex engine that does not support lookahead, you'll have to consider how to make up that !16. You can split files into two groups, those that start with 1, and aren't followed by 6, and those that start with anything else:

    somefile_(1[^6]|[^1]).*\.txt
    

    If you want to allow somefile_16_stuff.txt but NOT somefile_16.txt, these regexes above are not enough. You'll need to set your limit differently:

    somefile_(16.|1[^6]|[^1]).*\.txt
    

    Combine this all, and you end up with two possibilities, one which blocks out the single instance (somefile_16.txt), and one which blocks out all families (somefile_16*.txt). I personally think you prefer the first one:

    somefile_((16[^?%*:|"<>]|1[^6?%*:|"<>]|[^1?%*:|"<>])[^?%*:|"<>]*|1)\.txt
    somefile_((1[^6?%*:|"<>]|[^1?%*:|"<>])[^?%*:|"<>]*|1)\.txt
    

    In the version without removing special characters so it's easier to read:

    somefile_((16.|1[^6]|[^1).*|1)\.txt
    somefile_((1[^6]|[^1]).*|1)\.txt
    

提交回复
热议问题