简体   繁体   中英

How to match a pattern but a pattern on regex

If I have a list of filename eg:

member_1235435.dat
member_1243533.txt
member_1_1_2015.txt
member_1_3_2015_rejected.dat

How can I match all within a pattern of member_{number}.extension except those with _rejected ?

So far I have like this:

^Member_.*.*

I thought it will look like this, but it does not work.

^Member_.*(?!_rejected).*

I tried the first answer in comment

24646-MBPRS-Username:myapp Username$ ./src/myapp launcher:local ~/Desktop/myfilesdirectory /^member_(?:.(?!_rejected))*$/
-bash: !_rejected: event not found

I tried to escape ! sign, this is what I got

24646-MBPRS-Username:myapp Username$ ./src/myapp launcher:local ~/Desktop/myfilesdirectory /^member_(?:.(?\!_rejected))*$/
-bash: syntax error near unexpected token `('

FYI, the pattern will go through command line argument

如果可接受的名称在member_之后member_数字和_组合,则只需使用以下正则表达式即可:

^member_[\d_]+\.\w+$

The first answer works. I've used this code to test:

<?php
$s = [
    'member_1235435.dat',
    'member_1243533.txt',
    'member_1_1_2015.txts',
    'mber_1_1_2015.txt',
    'member_1_3_2015_rejected.dat'
];

echo preg_match('/^member_[\d_]+\.\w+$/', $s[1]) ? 'yes' : 'no';

In case you want to use a extension with 3 letters, use '/^member_[\\d_]+\\.\\w{3}$/' .

You can use the discard technique by using a regex like this:

.*rejected(*SKIP)(*FAIL)|^.*

Working demo

在此处输入图片说明

using the ".ext" as the terminator after the numerical term.

$ grep -Eo 'member_[0-9_]+\.(.*)$' file

member_1235435.dat
member_1243533.txt
member_1_1_2015.txt

In bash, filename patterns are not regexes. They are "globs" .

Even where regexes are possible, such as inside [[...]], lookahead assertions are not implemented.

However, you can use extended globs, as described in the bash guide linked above:

$ shopt -s extglob
$ echo member_!(*_rejected*).dat
member_1235435.dat
$ echo member_!(*_rejected*).*
member_1235435.dat
member_1243533.txt
member_1_1_2015.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