0

I've been trying to get a regular expression to work for my code for a while and am wondering if anyone knows a better way.

I've got a big chunk of text to parse and want to split it into an array based on the lines. This would be straightforward, right? Using regex:

var re:RegExp = /\n/;    
arr = content.split(re);

Easy. But I also want to only split on lines that do not have a space after them. I figured I'd use the \S character to match anything with a non-space character after the \n.

var re:RegExp = /\n\S/;    
arr = content.split(re);

However, this now removes the first letter of every line I'm splitting (because it's matching those letters).

What's the best way to:

  1. Ignore the spaces by using a caret (I tried something like /\n^\' '/ but no luck)?
  2. Not lose that \S character when splitting the string into an array?

2 Answers 2

3

Use lookahead in your pattern (so \S symbol won't be consumed as a split separator):

var re:RegExp = /\n(?=\S)/;    
arr = content.split(re);
Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate your solution! This answer works really well.
1

Additionally to raina77ow answer (using positive lookahead with \S), you can also use a negative lookahead with \s:

var re:RegExp = /\n(?!\s)/;    
arr = content.split(re);

Regular expression visualization

Comments

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.