Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - Javascript: Named Capture Groups

I need to match an expression and extract values from it using named groups.

Lets say this is my string:

var str = 'element=123'

So i want to match it using regex and extract the element and value.

I know how to do it is c#, I am trying to figure it out in JS.

This is my regex:

new RegExp(/^(<element>[A-Za-z0-9])+=[A-Za-z0-9]+$/);

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now, with ES2018, RegExp named capture groups are actually possible.

Here's an example already working in Chrome 64 (soon to be available also in Safari).

const isoDateExpression = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;

let match = isoDateExpression.exec('1999-12-31');
console.log(
    match.groups.year, // 1999
    match.groups.month, // 12
    match.groups.day, // 31
)

Syntax reference: https://github.com/tc39/proposal-regexp-named-groups

Firefox haven't decided yet, but here's an entry in Mozilla's issue tracker: https://bugzilla.mozilla.org/show_bug.cgi?id=1362154

Edit: Implemented in Firefox 78 and Safari 11.1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...