gpt4 book ai didi

javascript - 根据文本中出现的字符串填充数组

转载 作者:行者123 更新时间:2023-12-01 01:13:08 24 4
gpt4 key购买 nike

我需要用文本中的所有“特定出现”字符串填充一个数组。想象一下我有这样的文字:

  • “嗨,我叫鲍勃,我今年 20 岁,喜欢猫。[这里有很多文字]嗨,我叫迪伦,我今年 25 岁,喜欢狗。 [这里有很多文字]嗨,我的名字是铃鼓,我我30岁了,像乌龟”。[这里有很多文字]

所以我需要一个循环来搜索“嗨,mas name is”并获取直到句点/点的信息。所以我的输出会是这样的:

  • array[0] ->“嗨,我叫鲍勃,我今年 20 岁,喜欢猫。”
  • array[1] ->“嗨,我叫迪伦,我今年 20 岁,喜欢狗。”
  • array[3] -> “嗨,我叫 Tambourine,我今年 20 岁,喜欢乌龟。”

到目前为止,我只能从出现的次数中找到索引,但无法使用字符串填充数组,只能使用索引。

谢谢。

ps:文本是从 PHP 文件中提取的,因此出于安全和限制原因我使用 PHP

到目前为止我的代码:

  $html = $file;
$needle = "\$table->";
$lastPos = 0;
$positions = array();
$positions2 = array();


while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}

最佳答案

您可以使用此正则表达式来捕获所有句子。

[A-Z][^.]+\.?

<强> Demo

尝试这个 PHP 代码,

$s = "Hi, my name is Bob, I am 20 years old and like cats. Hi, my name is Dylan, I am 25 years old and like dogs. Hi, my name is Tambourine, I am 30 years old and like turtles";
preg_match_all('/[A-Z][^.]+\.?/', $s, $matches);
print_r($matches);

打印,

Array
(
[0] => Array
(
[0] => Hi, my name is Bob, I am 20 years old and like cats.
[1] => Hi, my name is Dylan, I am 25 years old and like dogs.
[2] => Hi, my name is Tambourine, I am 30 years old and like turtles
)

)

如果您使用 Javascript 进行编码,这里有一个 JS 演示,

var s = "Hi, my name is Bob, I am 20 years old and like cats. Hi, my name is Dylan, I am 25 years old and like dogs. Hi, my name is Tambourine, I am 30 years old and like turtles"
console.log(s.match(/[A-Z][^.]+\.?/g))

关于javascript - 根据文本中出现的字符串填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54995806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com