Regex find single N occurrence of ',' to replace
-
I’m wanting to do something seemingly simple, but I’m having a hard time creating the expression.
Say I have this text:
ANY,data,OF,any,SIZE,may,BE,inbetweenI’d like to select say the 4th comma and only that character:
ANY,data,OF,any**,**SIZE,may,BE,inbetweenI’m probably overlooking something fundamental in regex.
Thank you. -
@Nom said:
I’d like to select say the 4th comma and only that character
This seems overcomplicated, but it also seems to do the job:
Find what:
^(?-s)(?:.*?,){3}.*?(?=,)\K.
-
Thank you, regex seems to have its limits in regards to simplicity in certain use-cases.
-
@Nom said:
regex seems to have its limits in regards to simplicity in certain use-cases.
That’s like saying “C has certain limits in regards to simplicity in certain use-cases” or “the English language has certain limits in regards to simplicity in certain use-cases”. The more powerful something is, it sometimes makes it harder to express it “simply”.
The regex was able to express in 28 characters something you used 341 characters to describe. It used only 5 or 6 different elements of syntax to express that. It’s incredibly simpler than what you would have to write in raw C (ie, no external libraries) or assembler to do the same thing. Or even the English-based algorithm you’d have to write down to accomplish the same task, accounting for all the same edge cases that the regex syntax is naturally handling.
-
Okay, okay, everyone has called attention to my regex…now @guy038 will come along and do the same solution in about half as many characters. :(
BTW, I made a fat-finger mistake in the regex, but the beauty of it is that it still works. [The final character should be
,
(comma) instead of.
(period).]