1

I need to get information on variables and the only thing I have is the variable name. In this case let's say I need to get the chunk that belongs to SOME_LARGE_VARIABLE (every chunck starts with <0> and ends with <0>)

In other words how can I get the chunk <0>....SOME_LARGE_VARIABLE.....<0>

Note I do not want to have <0> ...... <0> ..... SOME_LARGE_VARIABLE .... <0>

<0>
    temp
<0>
    fo0
<0>
    BLA BLA BLA
    kjfsd
    foodskjdsf
    kj
<0>
    someVariable
<0>
    SOME_LARGE_VARIABLE
<0>

So far I have tried:

<0>[\s\S]*?SOME_LARGE_VARIABLE[\s\S]*?<0>

that finds <0> and then continues until it finds SOME_LARGE_VARIABLE and stops until <0>

note that will select everything

my temporary solution is:

<0>[\s\S]{1,25}SOME_LARGE_VARIABLE[\s\S]*?<0>

this restricts the selection to less than 25 characters. I think this is to risky because there might be two chuncks smaller than 25 characters


EDIT

In other words I want to end up with:

<0>
   SOME_LARGE_VARIABLE
<0>

and the only thing I have is SOME_LARGE_VARIABLE knowing that every chunk starts and ends with <0>

1 Answer 1

2

Instead of using .*? you could use (?:(?!<0>).)*, like so:

<0>(?:(?!<0>).)*SOME_LARGE_VARIABLE(?:(?!<0>).)*<0>

But you might as well be better off splitting the string on <0> and checking which parts match SOME_LARGE_VARIABLE.


Note that the expression will never match the second "chunk" in:

<0> SOME_LARGE_VARIABLE   will match
<0> SOME_LARGE_VARIABLE   will not match
<0>

Because the second <0> is consumed by the expression, not allowing it to match. (The splitting approach does not have this problem.)

You can fix that by using a lookahead tho:

<0>(?:(?!<0>).)*SOME_LARGE_VARIABLE(?:(?!<0>).)*(?=<0>)

If you want . to match line breaks as well, add (?s) in the beginning of the expression, like so:

(?s)<0>(?:(?!<0>).)*SOME_LARGE_VARIABLE(?:(?!<0>).)*(?=<0>)
4
  • this is how I ended up using it becuase of the multilines: <0>(?:(?!<0>)[\S\s])*SOME_LARGE_VARIABLE(?:(?!<0>)[\S\s])*(?=<0>)
    – Tono Nam
    Jun 19, 2012 at 23:44
  • @TonoNam, don't use [\s\S], use . with (?s).
    – Qtax
    Jun 19, 2012 at 23:45
  • When I tried your pattern it did not work. I had to replace the . with [\s\S]
    – Tono Nam
    Jun 19, 2012 at 23:46
  • Thanks! I will accept your answer as soon as stack overflow let's me.
    – Tono Nam
    Jun 19, 2012 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.