0

Trying to form a regular expression to match the pattern of keywords, the pattern I found is like

  • remove all words before : till a space occurs and all words after : till ) occurs.

find the term in this jsfiddle.

var newInput="keyword2:(content2) app keyword1:(content1) sos keyword:(content) das sad";

Im looking for an output like

app,sos,das,sad 
2
  • Does it have to be regular expressions? You could just split by space and filter items that start with 'keyword'.. Commented Sep 7, 2012 at 5:53
  • it doesnt have to be the term keyword... it could be random words... Commented Sep 7, 2012 at 5:55

2 Answers 2

2
newInput.replace(/[^:\s]+:\([^)]*\)\s*/g, '');  // "app sos das sad"

Explanation

[^:\s]+:   # any character (except ' ' and ':') in front of ':'  "keyword1:'"
\([^)]*\)  # any character enclosed in '(' ')'                   "(content2)"
\s*        # trailing spaces                                     " "

This returns a space-separated string. You would have to trim it and split at spaces (or replace them) yourself.

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

6 Comments

check the input "keyword2:(content2) app keyword1:(content1)";
@Sam Next time, do a better job at defining your inputs. With regular expression questions the answer can only be as good as the question is.
No. In your question a "searched word" always appears after a keyword:(contents) pattern.
"keyword2:(content2)" and "app" can come in any order
That's what I mean. Regex are extremely specific, so you must be extremely specific when stating your possible inputs. Otherwise you'll force people to guess, which is never a good thing. See modified answer. -- BTW, my answer was 99% of the way even with your more specific requirements. You could have made the last adjustment yourself, if you had tried.
|
1

You can try:

var words = newInput.replace(/[^\s]+:\([^\)]+\)\s+/g, "").split(/\s+/);

Which will produce an array of the words as:

["app", "sos", "das", "sad"]

If you want a comma-separated string as shown in the question then:

var words = newInput.replace(/[^\s]+:\([^\)]+\)\s+/g, "").split(/\s+/).join(", ")

2 Comments

check the input "keyword2:(content2) app keyword1:(content1)";
OK, sorry. I admit I found your description in the question a bit confusing, and you didn't show an example like that, but I guess you could change the regex pattern to /[^\s]+:\([^\)]+\)\s*/g (i.e., change the last + to a * to match optional whitespace), and then trim whitespace from the result.

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.