开发者

find word before second comma with regex

I want to store the word before the second comma in a string.

So if the string looks like this: Hello, my name is David, bla bla.

I want to set 开发者_JAVA技巧a variable $test = David


^[^,]*,[^,]*\b(\w+)\b,

^ -- The beginning of the string/line
[^ ] -- Any character not being ...
, -- ... a comma
* -- Zero or more of the preceding
, -- A comma
[^,]* -- Again, any character not being a comma, repeated zero or more times
\b -- A word boundary (zero width)
( ) -- A capturing group
\w -- Any word character
+ -- One or more of the preceding
\b -- A word boundary (zero width)
, -- A comma


Your regex could look something like this:

^[^,]*,[^,]*\b(\w+),

Match any sequence of non-commas, followed by the first comma, followed by more non-commas, then a word boundary and your actual word, and then the second comma.


this is web based nice tool which name is txt2re


And here is my approach:

<?php
    $input  = 'Hello, my name is David, bla bla.';
    $tmp    = substr( $input, 0, strpos( $input, ',', strpos( $input, ',' ) + 1 ) );
    $word   = substr( $tmp, strrpos( $tmp, ' ' ) + 1 );
    echo $word;
?>


<?php

    $s = "Hello, my name is David, bla bla.";

    preg_match ( "/[^,]*,[^,].* ([^,].*),.*/" , $s, $matches ); 

    // or shorter ..
    preg_match ( "/[^,]*,[^,]*\b(\w+),/" , $s, $matches );

    echo $matches[1];
    // => David

?>


$s = "Hello, my name is David, bla bla.";
$s = explode(',', $s);
$s = explode(' ', $s[1]);
$test = $s[sizeof($s)-1];

print $test;
'David'


Hokay, I know this is old, but I'm practicing…

How about /,.*?(\w+),/?

There's a saved explanation at this excellent tool: http://regex101.com/r/yA4gN5

  • , matches the character , literally
  • .*? matches any character (except newline)
    • Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
  • 1st Capturing group (\w+)
    • \w+ match any word character [a-zA-Z0-9_]
    • Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • , matches the character , literally

This regex (and some above) fails if David enters a non word character after his name, so 'David!,' and 'David ,' both fail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜