C
C#15mo ago
racoonknight

❔ confused with regex pattern

I’m new to regex, and basically i have a .txt file that I read from and from that file i need a specific part. Example text file: Key: Something 1234789 …,, )8382&wkdlpfofek.. /Key So I need to extract everything between Key and /Key and put it into a string. How would I go about with creating the regex pattern for that?
20 Replies
phaseshift
phaseshift15mo ago
Key:(.*)/Key You might need to add something for multi-line support
racoonknight
racoonknight15mo ago
What is the difference between .* and .*?
Servator
Servator15mo ago
.* is greedy match .*? is lazy match
mtreit
mtreit15mo ago
Greedy vs non-greedy matching is the difference.
racoonknight
racoonknight15mo ago
And to my understanding greedy means it will take the longest string that matches?
mtreit
mtreit15mo ago
Does the file have multiple sections matching that pattern? Yes
racoonknight
racoonknight15mo ago
no
mtreit
mtreit15mo ago
Then greedy vs lazy shouldn't matter in this case
racoonknight
racoonknight15mo ago
so purely for example if i had in my file Key: 1;kr;kr&: /Key Key: 17388848 Hajsifij^^^ Abbk 788 Uio /Key So greedy would take the longer one? Or would it take both and then I could use Groups[] to decide which i’d take?
mtreit
mtreit15mo ago
No, Greedy would take both as one match You need parentheses for grouping
racoonknight
racoonknight15mo ago
Ah I see, thank you
mtreit
mtreit15mo ago
I personally would probably not use Regex for this
racoonknight
racoonknight15mo ago
What would you use?
mtreit
mtreit15mo ago
Two calls to IndexOf and one call to Substring probably.
racoonknight
racoonknight15mo ago
But dont u need to know the specific index then?
mtreit
mtreit15mo ago
I generally find regex across multiple lines finicky That's what IndexOf gives you
racoonknight
racoonknight15mo ago
So you’d read the file into a string And then use indexOf to find the index of Key and /Key. And the substrin everything between?
mtreit
mtreit15mo ago
Yes. I'm not necessarily claiming that is superior to regex...though it might perform better Not sure
racoonknight
racoonknight15mo ago
I see. I didn’t think about that. Thank you
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.