简体   繁体   English

Javascript只获取正则表达式中匹配的文本

[英]Javascript get only matched text in regex

I have string like below我有像下面这样的字符串

BANKNIFTY-13-FEB-2020-31200-ce

I want to convert the string to 13-FEB-31200-ce我想将字符串转换为13-FEB-31200-ce

so I tried below code所以我尝试了下面的代码

str.match(/(.*)-(?:.*)-(?:.*)-(.*)-(?:.*)-(?:.*)/g)

But its returning whole string但它返回整个字符串

Two capture groups is probably the way to go.两个捕获组可能是要走的路。 Now you have two options to use it.现在您有两种选择来使用它。 One is match which requires you to put the two pieces together一种是比赛,需要您将两件放在一起

 var str = 'BANKNIFTY-13-FEB-2020-31200-ce' var match = str.match(/[^-]+-(\\d{2}-[AZ]{3}-)\\d{4}-(.*)/) // just reference the two groups console.log(`${match[1]}${match[2]}`) // or you can remove the match and join the remaining match.shift() console.log(match.join(''))

Or just string replace which you do the concatenation of the two capture groups in one line.或者只是字符串替换,您可以在一行中连接两个捕获组。

 var str = 'BANKNIFTY-13-FEB-2020-31200-ce' var match = str.replace(/[^-]+-(\\d{2}-[AZ]{3}-)\\d{4}-(.*)/, '$1$2') console.log(match)

Regex doesn't seem to be the most appropriate tool here.正则表达式在这里似乎不是最合适的工具。 Why not use simple .split ?为什么不使用简单的.split

 let str = 'BANKNIFTY-13-FEB-2020-31200-ce'; let splits = str.split('-'); let out = [splits[1], splits[2], splits[4], splits[5]].join('-'); console.log(out);

If you really want to use regexp,如果你真的想使用正则表达式,

 let str = 'BANKNIFTY-13-FEB-2020-31200-ce'; let splits = str.match(/[^-]+/g); let out = [splits[1], splits[2], splits[4], splits[5]].join('-'); console.log(out);

I would not use Regex at all if you know exact positions.如果您知道确切的位置,我根本不会使用正则表达式。 Using regex is expensive and should be done differently if there is way.使用正则表达式很昂贵,如果有办法,应该以不同的方式完成。 ( https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ ) https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/

const strArr = "BANKNIFTY-13-FEB-2020-31200-ce".split("-"); // creates array
strArr.splice(0,1); // remove first item
strArr.splice(2,1); // remove 2020
const finalStr = strArr.join("-");

If the pattern doesn't need to be too specific.如果模式不需要太具体。
Then just keep it simple and only capture what's needed.然后保持简单,只捕捉需要的东西。
Then glue the captured groups together.然后将捕获的组粘合在一起。

 let str = 'BANKNIFTY-13-FEB-2020-31200-ce'; let m = str.match(/^\\w+-(\\d{1,2}-[AZ]{3})-\\d+-(.*)$/) let result = m ? m[1]+'-'+m[2] : undefined; console.log(result);

In this regex, ^ is the start of the string and $ the end of the string.在这个正则表达式中, ^是字符串的开头, $是字符串的结尾。

You can have something like this by capturing groups with regex:您可以通过使用正则表达式捕获组来获得类似的东西:

在此处输入图片说明

 const regex = /(\\d{2}\\-\\w{3})(\\-\\d{4})(\\-\\d{5}\\-\\w{2})/ const text = "BANKNIFTY-13-FEB-2020-31200-ce" const [, a, b, c] = text.match(regex); console.log(`${a}${c}`)

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

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