String pattern help

So here’s an example of my string:
", stringnospace, string with space, string with space and numb3rs,"

Basically I want a string pattern that will give me the word inbetween the two commas. For example using the code

for i in string.gmatch(str, coolpattern) do
    print(i)
end

Should output:

, stringnospace,
, string with space,
, string with space and numb3rs,

What string pattern should I use?

Note: I have tried using "%b,," paired with string.sub however for some reason this seems to return every second item it should ouput (e.g. ‘stringnospace’ and ‘string with space and numb3rs’, skipping ‘string with space’

The , (%.) , pattern might work. The ,_ and _, (underscore = space) bits aren’t actually patterns, and instead are the hardcoded start and end values for the string. %. matches anything. Brackets () ‘capture’ anything inside them and returns what is captured instead of the entire match (so instead of returning , stringnospace , it returns stringnospace instead).

for text in string.gmatch(str, ', (%.) ,') do
    print(text)
end

Should output:

stringnospace
string with space
string with space and numbers

Also, for your first solution %b,,, it is not working because it is capturing everything within the first and last commas in the entire string. You could try doing %b,,- (or $b-,,, I’m unsure about the syntax) as the - modifier makes it match the smallest possible string.

4 Likes

I’m going to assume that you don’t want to include the commas or leading spaces in your captures, so actually you’re looking for an output of
stringnospace
string with space
string with space and numb3rs

The pattern you’re looking for is ,?%s*([^,]+),?. This will strip the commas & any spaces immediately following a comma. It will also ignore a leading comma at the start of the string or a trailing comma at the end of it.

2 Likes