简体   繁体   English

如何使用JavaScript中的正则表达式以优美的方式提取字符串?

[英]How to extract in elegant way the string using the regular expression in JavaScript?

I have the following script which I'm fetching as text: http://pastebin.com/c8XHN27N 我有以下脚本以文本形式获取: http : //pastebin.com/c8XHN27N

How can I cut/extract the desired URL from it using a regular expression? 如何使用正则表达式从中剪切/提取所需的URL?

I need to get the next value from the script above: t="https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt" 我需要从上面的脚本中获取下一个值: t="https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt"

Don't know if this is what you want. 不知道这是不是您想要的。 But this will help you extract all urls from the script file 但这将帮助您从脚本文件中提取所有网址

var src = "...";
var reg = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim
var urls = src.match(reg);
console.log(urls);
/* [
    "http://www.walkme.com/",
    "https://localhost/mt/resources/",
    "https://localhost/mt/lib/maketutorial_lib.js",
    "https://d3b3ehuo35wzeh.cloudfront.net",
    "https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt"
] */

https://regex101.com/r/aD4lW7/1 https://regex101.com/r/aD4lW7/1

There are 3 t vars in the script you passed, all with the same value inside, so there is no way to distinguish them. 您传递的脚本中有3 t变量,每个变量内部都有相同的值,因此无法区分它们。

Then we can pick up the first of the 3 with a simple: 然后,我们可以通过简单的方法选择三者中的第一个:

script = "...";
tVar = script.match(/t="[^"]*"/)[0] || '';
console.log(tVar); 
// "t="https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM