javascript 删除不需要的字符串部分。正则表达式/JS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28347014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:49:48  来源:igfitidea点击:

Remove unwanted part of String. Regex / JS

javascriptregex

提问by Daft

If I have a string which looks like this:

如果我有一个看起来像这样的字符串:

var myString = '73gf9y::-8auhTHIS_IS_WHAT_I_WANT'

What regex would I need to end up with:

我最终需要什么正则表达式:

'THIS_IS_WHAT_I_WANT'

The first part of my String will always be a random assortment of characters. Is there some regex which will remove everything up to THIS?

我的字符串的第一部分将始终是随机分类的字符。是否有一些正则表达式可以删除所有内容THIS

回答by Jonny 5

So you want to strip out everything from beginning to the first uppercase letter?

所以你想去掉从开头到第一个大写字母的所有内容?

console.log(myString.replace(/^[^A-Z]+/,""));

THIS_IS_WHAT_I_WANT

这就是我要的

See fiddle, well I'm not sure if that is what you want :)

看小提琴,我不确定这是否是你想要的:)



To strip out everything from start to the first occuring uppercase string, that's followed by _try:

要删除从开始到第一个出现的大写字符串的所有内容,然后_尝试:

myString.replace(/^.*?(?=[A-Z]+_)/,"");

This uses a lookahead. See Test at regex101;

这使用了前瞻。参见regex101 处的测试

回答by Amit Joki

Going by the input, you can use match. The character class [A-Z_]matches any capital letters and _(Underscore) and +quantifier along with $anchor matches the character class till the end of the string.

根据输入,您可以使用match. 字符类[A-Z_]匹配任何大写字母和_(下划线)和+量词以及$锚点匹配字符类直到字符串的末尾。

myString = myString.match(/[A-Z_]+$/)[0];
console.log(myString); // THIS_IS_WHAT_I_WANT

回答by TobyRush

Adding to Amit Joki's excellent solution (sorry I don't have the rep yet to comment): since matchreturns an array of results, if you need to remove unwanted characters from within the string, you can use join:

添加到 Amit Joki 的优秀解决方案(抱歉,我还没有代表发表评论):由于match返回结果数组,如果您需要从字符串中删除不需要的字符,您可以使用join

input = '(800) 555-1212';
result = input.match(/[0-9]+/g).join('');
console.log(result); // '8005551212'