Community

    • Login
    • Search
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search

    Regex find single N occurrence of ',' to replace

    Help wanted · · · – – – · · ·
    regex occurance
    3
    5
    433
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Nom
      Nom last edited by

      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,inbetween

      I’d like to select say the 4th comma and only that character:
      ANY,data,OF,any**,**SIZE,may,BE,inbetween

      I’m probably overlooking something fundamental in regex.
      Thank you.

      Alan Kilborn 1 Reply Last reply Reply Quote 0
      • Alan Kilborn
        Alan Kilborn @Nom last edited by

        @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.

        1 Reply Last reply Reply Quote 3
        • Nom
          Nom last edited by

          Thank you, regex seems to have its limits in regards to simplicity in certain use-cases.

          1 Reply Last reply Reply Quote 2
          • PeterJones
            PeterJones last edited by

            @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.

            Alan Kilborn 1 Reply Last reply Reply Quote 0
            • Alan Kilborn
              Alan Kilborn @PeterJones last edited by

              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).]

              1 Reply Last reply Reply Quote 1
              • First post
                Last post
              Copyright © 2014 NodeBB Forums | Contributors