0

I need to match data within a string in order to parse the data. The format for the data is follows

A*(anything)B*(anything)ABC*(anything)

The keys will always be A, B, ABC or DCE.

I have it working for the keys with the length of one character.

$(function() {

var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";

s.match(/(A|B|ABC|DCE)\*[^*]+(?!\*)/g).forEach(match => {
    var [k, v] = match.split('*');

    console.log(k + "->" + v);
});

});

However, this is the output (doesn't work with 1+ length keys

A->(anything)
B->(anything)AB
DCE->(anything)

The value is not always (anything) - it is dynamic.

I think the issue is with (?!*)/g

1
  • Are the desired values always in parentheses like that? Commented May 13, 2018 at 5:38

2 Answers 2

1

I managed to get your logic working using a formal regex matcher. The problem with your regex pattern is that you are using a negative lookahead to stop the match. Instead, use a positive lookahead which asserts that we have reached the next (A|B|ABC|DCE)* or the end of the string.

var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";
var regexp = /(A|B|ABC|DCE)\*(.*?)(?=(?:A|B|ABC|DCE)\*|$)/g;
var match = regexp.exec(s);
while (match != null) {
    print(match[0].split("\*")[0] + "->"+ match[0].split("\*")[1]);
    match = myRegexp.exec(myString);
}

Demo

Sign up to request clarification or add additional context in comments.

4 Comments

Great, this works like a charm. Is there a way to store "A|B|ABC|DCE" in a variable and then implement it into the regex from the variable?
@AhmedEnzea Yes, you may use a RegExp object constructor, see here. Just pass any string you wish to the constructor.
You are right about the placeholder! Deleted my answer and upvoted yours.
@Thefourthbird It's sometimes hard here to even figure out what is being asked. I appreciate your support.
0

why not using [^\)] instead of [^*]

var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";

// s.match(/[ABCDE]+\*[^\)]+\)/g).forEach(match =>
// or
s.match(/(A|B|ABC|DCE)\*[^\)]+\)/g).forEach(match => {
    var [k, v] = match.split('*');

    console.log(k + "->" + v);
});

2 Comments

This happens to work for the exact example input given, but it would fail if, for example, the content were this (and) that, or anything else which doesn't always terminate in closing parenthesis.
please update your anything so we know exactly the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.