简体   繁体   中英

Regular expression for splitting a string in Flex/Action Script

I have an array of Strings which I want to parse and create an ArrayCollection of Objects.

The Strings will be of the form "[1][2][3][4][5]". Where each number represents the following

  1. A name which contain any number of spaces and special characters
  2. Any number of spaces
  3. A number
  4. A single space
  5. A string "GB" always

Sample strings are:

  • StackOverflow 500 GB
  • Stack Over flow 100 GB
  • Stack!@#$%%^&*_ Flow 50 GB

I want to have a regular expression through which I can match the part [1] and [3](ex. StackOverflow and 500) and create objects with these fields.

I recommend using the split method to turn this into an array. If you can control the delimiter and make it a single character; I strongly recommend it. for example, something like this:

var myString :String = "1|2|3|4|5";
var myAray :Array = myString.split('|');

However, if you have no control over the string delimiter you can use a regular expression. conceptually something like this:

var myString :String = "[1][2][3][4][5]";
var regEx : RegExp = new RegExp([\[]|[\]]|[\[\]]);
var myAray :Array = myString.split(regEx);

You should assume my regular expression is imperfect; but more info on creating them here . You may get empty array item at the beginning and end since your string starts and ends with a delimiter.

I am not familiar with Flex/Action Script but can suggest general regex.

(.*)(\s+)(\d+)(\s)(GB)

Create objects with content captured in \\1 and \\3

Here, each pair of parenthesis captures [1] to [5] contents, mentioned in the question, into \\1 to \\5 respectively.

Check this in action: http://regex101.com/r/xF4qS8

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