PHP preg_match question

人走茶凉 提交于 2019-12-13 06:32:28

问题


How can I match the three words in the following string with a Perl compatible regular expression?

word1#$word2#$word3

I don't know the actual words "word1, word2 and word3" in advance. I only know the separator, which is #$.

And I can't use the word boundary as I have a multibyte encoding. This means for instance that the string can contain non-ASCII characters like umlauts which are not detected by the \w control character.


回答1:


Try this regular expression:

/(\w+)#\$(\w+)#\$(\w+)/

Edit   After your provided us with more information (see the comments to this answer):

/((?:[^#]+|#[^$])*)#\$((?:[^#]+|#[^$])*)#\$((?:[^#]+|#[^$])*)/



回答2:


#!/usr/bin/perl

use strict;
use warnings;

my $x = 'word1#$word2#$word3';
print $_, "\n" for split /#\$/, $x;



回答3:


$str = explode('#$', $str);

Regex is overkill for this.




回答4:


A split function might be useful although it depends what you want to do with the line.

here is an example though.

my $line = "word1#$word2#$word3"
my @words = split('#$', $line)



回答5:


This will work for any string that has 2 #

/([^#]+)\#\$([^#]+)\#\$([^#]+)/



回答6:


/([^#]*?)#\$([^#]*?)#\$([^#]*)/


来源:https://stackoverflow.com/questions/1179165/php-preg-match-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!