开发者

Regular expression for end of line phrase

I am grabbing a block of text, and within this block there will be a line containing a phrase that ends with "WITH PASSWORD k开发者_StackOverflow中文版EqHqPUd" where kEqHqPUd is a dynamically generated password. What is a simple regular expression for grabbing just the password within this?

I'm using PHP.


preg_match('/WITH PASSWORD (.*)$/im', $block, $matches);
//result in $matches[1]

The key is the "m" modifier.


I am not sure how you define "phrase that ends"... But if you mean "a sentence ends with the password, but could be followed by another sentence", then a solution could be:

$text = <<<TEXT
This is some
text and there is a sentence that ends
with WITH PASSWORD kEqHqPUd. Is that
matched ?
TEXT;

$matches = array();
if (preg_match('/WITH PASSWORD ([\w\d]+)/', $text, $matches)) {
    var_dump($matches[1]);
}

This will only work, though, if the password only contains letters and/or numbers -- but it will work if there is something after "the end of the phrase".


If you meant that the password is the last thing in the whole string, you could use something like this:

$text = <<<TEXT
This is some
text and there is a sentence that ends
with WITH PASSWORD kEqHqPUd
TEXT;

$matches = array();
if (preg_match('/WITH PASSWORD (.+)$/m', $text, $matches)) {
    var_dump($matches[1]);
}

Note that the $ sign means "end of string".


Assuming that PHP accepts standard regex patterns, "WITH PASSWORD (.+)+$" should work, where the password will be placed in the first capture group.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜