简体   繁体   中英

regular expression that matches the below pattern

I'm not good in regular expression, but today I faced an unavoidable situation, So I need a regular expression that matches the case below:

|hhas.jpg||sd22-9393das.png||8jjas.png||IMG00338-20110109.jpg|

I tried this regex : /(?<=\\|)(\\w|\\d+\\.\\w+)(?=\\|)/i but not getting the desired results...

I want to match all the strings by using preg_match function of PHP between two | signs ie hhas.jpg, sd22-9393das.png etc...

Use this..

preg_match_all('/\|(.*?)\||/', $str, $matches);
print_r(array_filter($matches[1]));

OUTPUT :

Array
(
    [0] => hhas.jpg
    [1] => sd22-9393das.png
    [2] => 8jjas.png
    [3] => IMG00338-20110109.jpg
)

Demonstration

enter image description here

You can use the following regex:

/\\|([^|]*)\\|/gi

Demo

Matched strings:

1. hhas.jpg
2. sd22-9393das.png
3. 8jjas.png
4. IMG00338-20110109.jpg

your expression :

/(?<=\|)(\w|\d+\.\w+)(?=\|)/i

pretty well written , but just has a few minor flaws

  • when you say \\w that is only one character.

  • the OR condition

  • \\d+\\.\\w+ will match only when it meets the same order. ie list of digits first followed by a . and then followed by letters or digits or underscore.

better change your regex to :

/(?<=\|)(.*?)(?=\|)/ig

this will give you anything which is between | s

also IMHO , using lookarounds for such a problem is an overkill. Better use :

/\|(.*?)\|/ig

Try without using regular expression.

explode('||', rtrim(ltrim ('|hhas.jpg||sd22-9393das.png||8jjas.png||IMG00338-20110109.jpg|','|'),'|'));

Output:

Array ( [0] => hhas.jpg [1] => sd22-9393das.png [2] => 8jjas.png [3] => IMG00338-20110109.jpg ) 

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