Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to capture strings by newlines?

I'm trying to capture substrings with :match, in which each substring is a line of a multi-line string. My attempt:

a1,a2 = ([[
	Setting Debug True
	Setting GhostScript True
]]):match('(%w+)\n(%w+)')

warn(a1) warn(a2)

It warns nil for both.

Also tried [%c%Z] instead of \n, but it separates spaces too.

Help is appreciated.

1 answer

✓ Accepted answer

Your Problem

The reason that you were not getting anything returned had nothing to with the string pattern, but rather had to do with how you formatted your String. You have whitespace characters (more specifically tabs) in front of each line of your String. If you remove those you will no longer get nil.

However, now another problem occurs. When you run it you'll see True and Setting in your output. This is because it is looking for sequences of alphanumeric characters separated by a newline and will not pick up on the spaces.

The Solution

You can use a Sets in order to combine character classes, making it search for sequences that contain different types characters. In your case we are looking for two sequences of both alphanumeric characters and spaces separated by a newline character. This can be represented through this string pattern:

"([%w ]+)\n([%w ]+)"

This uses the set [%w ] (yes that space is deliberate) and the operator + to capture every word and space on the first two lines.

2 comments

0

Very nice.

0

Works perfectly, thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.