Regular expression for finding some words

Full Text = "........ -B D:\ABC -C ........."

I want to get D:\ABC between -B and -C.

How can I get words using Regular expression?

3 answers

  • answered 2019-04-15 06:00 MichaƂ Turczyn

    You could use a pattern with lookarounds (?<=-B)\s*(\S*)\s*(?=-C)

    Explanation:

    (?<=-B) - positive lookbehind, to assert that what is preceeding is -B

    \s* - zero or more of whitespace characters

    (\S*) - zero or more non-whitespace characters, stored in capturing group - this is string that you want to get

    (?=-C) - positive lookahead, to assert that what is after is -C

    Demo

  • answered 2019-04-15 06:00 Allan

    You can use the following sample:

    if ($string -cmatch '\s-B\s*(.+?)\s*-C\s'){$sub = $matches[1]}
    

    Hypothesis: there is no -C between -B and -C and only one -B and one -C in the correct order

  • answered 2019-04-15 06:19 Lee_Dailey

    presuming the following is true ...

    • only ONE -B
    • followed by only the wanted text
    • followed by only ONE -C

    ...then this otta work >> '^.+ -B (.+) -C .+$' <<

    what it does ...

    • start of line
    • one or more chars
    • space, hyphen, B, space
    • a capture group for everything after that and before the next pattern
    • space, hyphen, C, space
    • one or more characters
    • end of line