c_minor_team
c_minor_team

Reputation: 23

Match all regex start with but not end with characters

i have an array of words i want to match all with starting '___' but some words also having '___' at the end . but i do not want to match these words

here is my word list

___apis
___db_tables
___groups
___inbox_messages
___sent_messages
___todo
___users
___users_groups
____4underscorestarting
sinan
sssssssssss
test_______dfg
testttttt
tet____
tttttttttt
uuuuuuuu
vvvvvvvvvvvv
wwwwwwww
zzzzzzzzzz

i want to match only these words

___apis
___db_tables
___groups
___inbox_messages
___sent_messages
___todo
___users
___users_groups

i do not want to match these words

tet____
test_______dfg
____4underscorestarting

this is how it looks like when i try

enter image description here

Upvotes: 2

Views: 136

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using preg_grep function:

// $arr is your initial array of words
$matched = preg_grep("/^_{3}[^_].*/", $arr);
print_r($matched);

The output:

Array
(
    [0] => ___apis
    [1] => ___db_tables
    [2] => ___groups
    [3] => ___inbox_messages
    [4] => ___sent_messages
    [5] => ___todo
    [6] => ___users
    [7] => ___users_groups
)

Update: To get the opposite matches use one of the following:

  • regex pattern: /^(?!_{3})\w*/
  • set the third argument of preg_grep function as PREG_GREP_INVERT(... preg_grep("/^_{3}[^_].*/", $arr, PREG_GREP_INVERT))

http://php.net/manual/en/function.preg-grep.php

Upvotes: 2

ssubra
ssubra

Reputation: 1

    ^_{3}.*[^(_{3})]$ 
  1. Starts(^) with 3 '_' _{3}
  2. Can contain anything in the middle .*
  3. Does not end($) in 3 '' [^({3}]

Upvotes: 0

vks
vks

Reputation: 67968

^___[a-z].*

this should do it for you.See demo.

https://regex101.com/r/hHRg8d/1

Upvotes: 1

Related Questions