Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to capture strings by newlines?

Asked by
RafDev 109
8 years ago

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

Log in to vote
3
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

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.

0
Very nice. XAXA 1569 — 8y
0
Works perfectly, thanks! RafDev 109 — 8y
Ad

Answer this question