Get only the first occurrence of R1: with regex

Asked

Viewed 140 times

1

I have the following text::

R1:C1[6]|R1:C1[12]-[P1_G]

I need to get only the first R1:.

I tried doing a lazy regex R[\d+]?: ,but I didn’t get the result I needed and I didn’t understand why it didn’t work either.

I am using the https://regex101.com/ as engine to test this situation that will be implemented in C# after.

  • Tries R(\d+):?, without the flag g

  • I tried and didn’t solve

  • 1- Can you simplify to R\d+: (or R\d*: if the number is optional), see. Or else ^R\d+, but only if the R always appears at the beginning. 2- What language/engine did you use and what was the result? Usually languages have different options to get all occurrences or only the first (see here the difference to the previous link), and still there are Engins that do not support the syntax \d, then it would be interesting you [Edit] the question and put more these details.

  • https://regexr.com/48m63

  • Just remembering that if you want to extract the value you need to create a capture group using parentheses: (R\d+)

  • 1

    If it was the \d that gave error, you can exchange for R[0-9]+: - still, it is not clear if the error was that brought all occurrences (and in this case, it would be good to know which language used, because in each one the way of doing it is different), or if there was syntax error in regex, or something else (ie, please click on [Edit] and put this information in the question)

  • @Andersoncarloswoss Depending on how you do it, you don’t need the capture group: https://ideone.com/ClBTOi. (all the more reason :-) )

  • @hkotsubo I used https://regex101.com/ as engine. Then I will implement the solution in C#. This R+: solution worked, I thought I would need to use the ?

  • 2

    In regex101 just take out the flag g (right-hand flag, just after the regex): https://regex101.com/r/sw0ryP/1/ - O ? means "optional". But if the digits are optional, you can use R\d*:. The + means "one or more occurrences", and * that is to say "zero or more occurrences"

  • Thanks @hkotsubo I didn’t know that detail.

Show 5 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.