如何在正则表达式中获取字符串并在匹配字符串后删除其他字符串

How to get a string in regex and delete other after matching the string

我的输入如下

1 等等等等@username_。废话废话废话

我需要的输出如下 用户名_。

现在,我做这个表达

^.*\@([a-zA-Z0-9\.\_]+)$

以下工作

1 等等等等@username_。

但如果我将它用于整行,它就不起作用

所以它获取用户并在用户之前删除 但是我如何让它在获得用户后删除其余部分

注意我用的是regex101来测试,如果你有更好的工具请写在下面。

您的模式使用 ^$ 这意味着它需要完全匹配,您的模式只是部分匹配。
通过添加 .* 它成为一个完整的正则表达式,并且按预期匹配。

"/^.*\@([a-zA-Z0-9\.\_]+).*$/"

https://3v4l.org/i4pVd

另一种方法是像这样使用部分正则表达式。
它会跳过 @ 之前的任何内容,然后将所有内容捕获到一个点

$str = "1 blah blah blah @username_. sblah sblah sblah";
preg_match("/.*?\@(.*?\.)/", $str, $match);

var_dump($match);

https://3v4l.org/mvBYI

要匹配示例数据中的用户名,您可以 preg_match and omit the $ to assert the position at the end of the string as in this demo。请注意,您不必转义 @ 字符中的点和下划线 class.

要获取示例数据中的用户名,您还可以使用:

@\K[\w.]+

那会匹配

  • @字面匹配
  • \K忘记之前匹配的内容
  • [\w.]+匹配1+次单词字符或点

Regex demo

$re = '/@\K[\w.]+/';
$str = '1 blah blah blah @username_. sblah sblah sblah @test';
preg_match($re, $str, $matches);
echo $matches[0]; // username_.

Demo php