简体   繁体   中英

Cannot extract parts of a string

I have a string like this : SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: .

Using Javascript, I would like to extract the two IDs (which can be different) : 6E5F5E0D-0CA4-426C-A523-134BA33369D7 and C5DD2ADA-E0C4-4971-961F-233789297FE9 .

I'm using this regular expression : ^SPList\\:(?:[0-9A-Za-z\\-]+)\\?SPWeb\\:(?:[0-9A-Za-z\\-]+)\\:$ .

I expect this expression to extract into two matching groups the two IDs.

By now, my code is :

var input = "SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:";

var myregex = /^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$/g;

var match = input.match(myregex);

var listId = match[0];
var webId = match[1];

However, this is not working as expected. The first match contains the whole string, and the second match is undefined.

What is the proper way to extract my ID's?

Here is a jsfiddle that illustrate my issue.

This should suit your needs:

var regex = /^SPList:([0-9A-F-]+)[?]SPWeb:([0-9A-F-]+):$/g;
var match = regex.exec(input);
var listId = match[1];
var webId = match[2];

I simply replaced the non-capturing groups of your initial regex by capturing groups, and used regex.exec(input) instead of input.match(regex) to get the captured data. Also, since the IDs seem to be hexadecimal values, I used AF instead of AZ .

try this:

        var myregex = /[^\:]([0-9A-Z\-]+)[^\?|\:]/g;
        var match = input.match(myregex);
        alert("listID: " + match[1] + "\n" + "webID: " + match[3]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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