解析格式化字符串——隔离带引号的子字符串和大括号 UUID

发布于 2024-09-03 11:07:55 字数 151 浏览 1 评论 0原文

我正在尝试解析操作系统实例及其唯一标识符的列表。我正在寻找一种解决方案来解析文本字符串,并将值传递给两个变量。待解析的字符串如下:

"Ubuntu 9.10" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}

I am trying to parse a list of operating system instances with their unique identifiers. I am looking for a solution to parse a text string, and pass the values into two variables. The string to be parsed is as followed:

"Ubuntu 9.10" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

转瞬即逝 2024-09-10 11:07:55

我一直在寻找借口阅读 sscanf() 的文档:

sscanf($s, '"%[^"]" {%[^}]}', $os, $ident);
echo $os, "<br>", $ident;

后续: 出于兴趣,目前对此问题有三个答案:

sscanf: 0.92999792098999 seconds
preg_match: 4.73761510849 seconds
str_replace x2 + preg_split: 3.7644839286804 seconds

此处为基准。有趣的是,两个 str_replace() 和一个 preg_split()preg_match() 更快。

I've been looking for an excuse to read the docs for sscanf():

sscanf($s, '"%[^"]" {%[^}]}', $os, $ident);
echo $os, "<br>", $ident;

Followup: For interest's sake, out of the three answers currently on this question:

sscanf: 0.92999792098999 seconds
preg_match: 4.73761510849 seconds
str_replace x2 + preg_split: 3.7644839286804 seconds

Benchmark here. Funny that two str_replace() and a preg_split() are faster than the preg_match().

许你一世情深 2024-09-10 11:07:55

您可以使用正则表达式来匹配您需要的组:

$str = '"Ubuntu 9.10" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}';
preg_match('/^"(.*)" {(.*)}$/', $str, $matches);

您可以根据值缩小正则表达式的范围(例如第二个 .* 可以是 [0-9a-f-]+),但这就足够了。 $matches[1] 将为“Ubuntu 9.10”,$matches[2] 将为“40f2324d-a6b2-44e4-90c3-0c5fa82c987d”

You can use regular expressions to match the groups you need:

$str = '"Ubuntu 9.10" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}';
preg_match('/^"(.*)" {(.*)}$/', $str, $matches);

You can make the regular expression narrower based on the values (e.g. the second .* could be [0-9a-f-]+), but that's sufficient. $matches[1] will be "Ubuntu 9.10", and $matches[2] will be "40f2324d-a6b2-44e4-90c3-0c5fa82c987d"

稚然 2024-09-10 11:07:55

这使用 str_replace 和 preg_split

$s = "\"Ubuntu 9.10\" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}";
$s = str_replace("\" ", "|", $s); // substitute middle quotation mark and space for a delimiter
$s = str_replace("\"", "", $s); // remove quotation marks
$vars = preg_split('/\|/', $s); // split by delimiter
print_r($vars);

This gets the two strings as first and second elements of a string array using str_replace and preg_split:

$s = "\"Ubuntu 9.10\" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}";
$s = str_replace("\" ", "|", $s); // substitute middle quotation mark and space for a delimiter
$s = str_replace("\"", "", $s); // remove quotation marks
$vars = preg_split('/\|/', $s); // split by delimiter
print_r($vars);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文