简体   繁体   中英

Retrieving several capturing groups recursively with RegExp

I have a string with this format:

#someID@tn@company@somethingNew@classing@somethingElse@With

There might be unlimited @-separated words, but definitely the whole string begins with #

I have written the following regexp, though it matches it, but I cannot get each @-separated word, and what I get is the last recursion and the first (as well as the whole string). How can I get an array of every word in an element separately?

(?:^\#\w*)(?:(\@\w*)+) //I know I have ruled out second capturing group with ?: , though doesn't make much difference.

And here is my Javascript code:

var reg = /(?:^\#\w*)(?:(\@\w*)+)/g;

var x = null;


while(x = reg.exec("#someID@tn@company@somethingNew@classing@somethingElse@With"))
{
  console.log(x); 
}

And here is the result (Firebug, console):

["#someID@tn@company@somet...sing@somethingElse@With", "@With"]


0
    "#someID@tn@company@somet...sing@somethingElse@With"

1
    "@With"

index
    0

input
    "#someID@tn@company@somet...sing@somethingElse@With"

EDIT : I want an output like this with regular expression if possible:

["#someID", "@tn", @company", "@somethingNew", "@classing", "@somethingElse", "@With"]

NOTE that I want a RegExp solution. I know about String.split() and String operations.

You can use:

var s = '#someID@tn@company@somethingNew@classing@somethingElse@With'
if (s.substr(0, 1) == "#")
    tok = s.substr(1).split('@');    
    //=> ["someID", "tn", "company", "somethingNew", "classing", "somethingElse", "With"]

You could try this regex also,

((?:@|#)\w+)

DEMO

Explanation:

  • () Capturing groups. Anything inside this capturing group would be captured.
  • (?:) It just matches the strings but won't capture anything.
  • @|# Literal @ or # symbol.
  • \\w+ Followed by one or more word characters.

OR

> "#someID@tn@company@somethingNew@classing@somethingElse@With".split(/\b(?=@|#)/g);
[ '#someID',
  '@tn',
  '@company',
  '@somethingNew',
  '@classing',
  '@somethingElse',
  '@With' ]

It will be easier without regExp:

var str = "#someID@tn@company@somethingNew@classing@somethingElse@With";
var strSplit = str.split("@");
for(var i = 1; i < strSplit.length; i++) {
    strSplit[i] = "@" + strSplit[i];
}
console.log(strSplit);
// ["#someID", "@tn", "@company", "@somethingNew", "@classing", "@somethingElse", "@With"]

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