Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript-从字符串中提取一些单词_Javascript_String_Split - Fatal编程技术网

JavaScript-从字符串中提取一些单词

JavaScript-从字符串中提取一些单词,javascript,string,split,Javascript,String,Split,我有这样的字符串: const myString = '[12m[99mSOME STRING 1: [bla[bla[88mSOMETHING 2[00m[' 我想在单独的变量中从这个字符串中提取一些字符串1和字符串2。 字符串将始终保持不变,除了某些字符串1和某些字符串2的一部分 因为这个原因,我不能使用includes'somestring1'来表示这个 [99m到:之间的所有内容都是第一个需要的字符串 [88m到[88m]之间的所有内容都是第二个需要的字符串 预期结果: 说明: \[9

我有这样的字符串:

const myString = '[12m[99mSOME STRING 1: [bla[bla[88mSOMETHING 2[00m['
我想在单独的变量中从这个字符串中提取一些字符串1和字符串2。 字符串将始终保持不变,除了某些字符串1和某些字符串2的一部分

因为这个原因,我不能使用includes'somestring1'来表示这个

[99m到:之间的所有内容都是第一个需要的字符串

[88m到[88m]之间的所有内容都是第二个需要的字符串

预期结果:

说明:

\[99m // Find the exact string "[99m"
(...) // Capture the string that matches the enclosed expression
[^:]+ // Match one or more characters until a ":" character is met
.*?   // Match all characters until the next expression finds a match
\[88m // Find the exact string "[88m"
(...) // Capture the string that matches the enclosed expression
[^[]+ // Match one or more characters until a "[" character is met
exec的输出将为null或3个条目的数组。第一个条目可以忽略,但下两个条目对应于括号中捕获的字符串

注意:这假设您的第一个字符串永远不会包含:并且您的第二个字符串永远不会包含[字符]


这是完整字符串还是子字符串?@harmandepsingkalsi这正是完整的myString,它看起来是什么样子。请在string2:var string2=str.substringstr.indexOf[88m+4,str.indexOf'[00m';以及string 1:var string1=str.substringstr.indexOf[99m+4,str.indexOf':'中尝试此操作;
regex = /\[99m([^:]+).*?\[88m([^[]+)/
myString = '[12m[99mSOME STRING 1: [bla[bla[88mSOMETHING 2[00m['
match = regex.exec(myString)
if (match) {
  var [ ignoreThis, string1, string2 ] = match
}

console.log("string1", string1)
// "SOME STRING 1"
console.log("string2", string2)
// "SOMETHING 2"
\[99m // Find the exact string "[99m"
(...) // Capture the string that matches the enclosed expression
[^:]+ // Match one or more characters until a ":" character is met
.*?   // Match all characters until the next expression finds a match
\[88m // Find the exact string "[88m"
(...) // Capture the string that matches the enclosed expression
[^[]+ // Match one or more characters until a "[" character is met