简体   繁体   English

我的正则表达式有什么问题?

[英]What's wrong in my regular expression?

I need to get from the line below only these parts: Jony, Smith and example-free@wpdevelop.com 我只需要从下面几行中获得:乔尼(Jony),史密斯(Smith)和example-free@wpdevelop.com

which, as you can see, they are between ^ and ~. 如您所见,它们在^和〜之间。

text^name1^Jony~text^secondname1^Smith~text^email1^example-free@wpdevelop.com~

to do this I tried: 为此,我尝试过:

preg_match_all ('/\^(.*?)\~/', $row['form'], $res);

For the name it displays: ^name1^Jony~ for the second name: ^secondname1^Smith~ and email: ^email1^example-free@wpdevelop.com~ 对于名称,它显示: ^ name1 ^ Jony〜 ,第二个名称: ^ secondname1 ^ Smith〜和电子邮件: ^email1^example-free@wpdevelop.com~

As you can see the word "text" has already disappeared, but not the ^, name1, secondname1, email1 and ~ 如您所见,“文本”一词已消失,但^,name1,secondname1,email1和〜却不消失。

Can you tell me what's wrong in my regular expression? 您能告诉我我的正则表达式有什么问题吗?

change .* to [^^]* meaning "Any character excluding ^ " .*更改为[^^]*表示“ ^ 之外的任何字符”

<?php
$str = 'text^name1^Jony~text^secondname1^Smith~text^email1^example-free@wpdevelop.com~';

preg_match_all ('/\^([^^]*?)\~/', $str, $res);

var_dump($res);

/*
//output 

$ php scratch.php
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "^Jony~"
    [1]=>
    string(7) "^Smith~"
    [2]=>
    string(28) "^example-free@wpdevelop.com~"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "Jony"
    [1]=>
    string(5) "Smith"
    [2]=>
    string(26) "example-free@wpdevelop.com"
  }
}
*/

Your regex needs to be '/\\^([^\\^]*?)\\~/' ,you're using . 您的正则表达式必须为'/\\^([^\\^]*?)\\~/' ,您正在使用. , which selects ^ . ,它选择^ You need to not select ^ using [^\\^] rather than . 您无需使用[^\\^]而不是来选择^ . .

This is better: 这个更好:

<?php

$string = 'text^name1^Jony~text^secondname1^Smith~text^email1^example-free@wpdevelop.com~';

preg_match_all('/\^.+?\^(.+?)~/', $string, $matches);

var_dump($matches);

The result in $matches will be: $ matches的结果将是:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(12) "^name1^Jony~"
    [1]=>
    string(19) "^secondname1^Smith~"
    [2]=>
    string(35) "^email1^example-free@wpdevelop.com~"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "Jony"
    [1]=>
    string(5) "Smith"
    [2]=>
    string(26) "example-free@wpdevelop.com"
  }
}

I added this .+?\\^ part to the regular expression, it matches the text between the two ^ characters. 我在正则表达式中添加了。+?\\ ^部分,它与两个^字符之间的文本匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM