从由下划线分隔的文本中获取特定字符串

时间:2015-11-13 11:39:00

标签: javascript

我正试图从下面的文字中获取特定的字符串:

var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";

从此我必须得到以下字符串:“LAST”,“BRANCH”和“JENKIN”。 我使用下面的代码来获得“JENKIN”;

var result = str.substr(str.lastIndexOf("_") +1);

它将获得结果“JENKIN.bin”。我只需要“JENKIN”。 此外,输入字符串str有时也包含此“.bin”字符串。

6 个答案:

答案 0 :(得分:2)

使用substring()函数,您可以通过定义开始和结束位置来提取所需的文本。您已经使用str.lastIndexOf("_") +1找到了起始位置,并使用str.indexOf(".")向substring()函数添加结束位置将为您提供所需的结果。

var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));

答案 1 :(得分:1)

您可以使用String.prototype.split通过给定的分隔符将字符串拆分为数组:



var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';

var parts = str.split('_'); 
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];

document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];




答案 2 :(得分:1)

这取决于模式的可预测性。怎么样:

var parts = str.replace(/\..+/, '').split('_');

然后部分[0]是001AN,部分[1]是最后的等等

答案 3 :(得分:1)

尝试使用String.prototype.match()RegExp /([A-Z])+(?=_B|_H|\.)/g匹配任意数量的大写字母,后跟"_B""_H""."



var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)




答案 4 :(得分:1)

我不知道你为什么这么想,但这个例子会有所帮助。

最好写出你想要的东西。

str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'

find = ['LAST', 'BRANCH', 'JENKINS']

found = []

for item in find:
    if item in str:
        found.append(item)

print found # ['LAST', 'BRANCH']

答案 5 :(得分:1)

你可以这样做:

var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);

console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN

通过这种方式,您可以随时重复使用RegExp,也可以在其他语言中使用。

相关问题