Regex pattern to match a word based on previous and next word?Match all occurrences of a regexRegular expression to match a line that doesn't contain a wordHow to negate specific word in regex?RegEx match open tags except XHTML self-contained tagsGreedy vs. Reluctant vs. Possessive QuantifiersCheck whether a string matches a regex in JSRegex - Return previous AND next word from matchRegex match a string that doesn't contains a stringJavascript Regex - match capital/upperacase letter in a middle of a word (in a sentence)?NOT words in Regex Pattern

Could Europeans in Europe demand protection under UN Declaration on the Rights of Indigenous Peoples?

Transistor power dissipation rating

Are there any satellites in geosynchronous but not geostationary orbits?

Simplest instruction set that has an c++/C compiler to write an emulator for?

Why is the Intel 8086 CPU called a 16-bit CPU?

Integration using partial fraction is wrong

Company looks for long-term employees, but I know I won't be interested in staying long

Is it possible to have a career in SciComp without contributing to arms research?

Last-minute canceled work-trip means I'll lose thousands of dollars on planned vacation

Applying for jobs with an obvious scar

What is the mistake in this solution?

Making a Dataset that emulates `ls -tlra`?

When will the last unambiguous evidence of mankind disappear?

Why aren't there any women super Grandmasters (GMs)?

Heatsink on underside of PCB

How to determine Platform Event Size in Apex to ensure to be within < 1 MB

How to get a type of "screech" on guitar

Why isn't a binary file shown as 0s and 1s?

Three Subway Escalators

How to not confuse readers with simultaneous events?

Suggestions for how to track down the source of this force:source:push error?

Why do space operations use "nominal" to mean "working correctly"?

Demographic consequences of closed loop reincarnation

Why teach C using scanf without talking about command line arguments?



Regex pattern to match a word based on previous and next word?


Match all occurrences of a regexRegular expression to match a line that doesn't contain a wordHow to negate specific word in regex?RegEx match open tags except XHTML self-contained tagsGreedy vs. Reluctant vs. Possessive QuantifiersCheck whether a string matches a regex in JSRegex - Return previous AND next word from matchRegex match a string that doesn't contains a stringJavascript Regex - match capital/upperacase letter in a middle of a word (in a sentence)?NOT words in Regex Pattern






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to highlight a word based on the previous and next word matching with specific customer requirements.



A word should be highlighted only when previous and next word doesn't start with CAPS.



I have created regex "(?!bA-Zb)sSouls+(?!s[A-Z,0-9])" but it's also highlighting "Souls" with previous word that starts with capital.



https://regex101.com/r/wPmijX/2



In this case, "Souls" next to "Dark" should not be highlighted as it starts with caps. Only "Souls" in the second paragraph should be highlighted. Event "Souls" in the third paragraph should not be highlighted as "Game" start with capital letter.










share|improve this question






















  • You may use groups and then post-process the results, see ((?:^|b[a-z]w*)s+)(Souls)(?!s+[A-Z0-9])

    – Wiktor Stribiżew
    Mar 26 at 11:36











  • Thanks, That worked for me.

    – nishant
    Mar 26 at 13:47

















0















I am trying to highlight a word based on the previous and next word matching with specific customer requirements.



A word should be highlighted only when previous and next word doesn't start with CAPS.



I have created regex "(?!bA-Zb)sSouls+(?!s[A-Z,0-9])" but it's also highlighting "Souls" with previous word that starts with capital.



https://regex101.com/r/wPmijX/2



In this case, "Souls" next to "Dark" should not be highlighted as it starts with caps. Only "Souls" in the second paragraph should be highlighted. Event "Souls" in the third paragraph should not be highlighted as "Game" start with capital letter.










share|improve this question






















  • You may use groups and then post-process the results, see ((?:^|b[a-z]w*)s+)(Souls)(?!s+[A-Z0-9])

    – Wiktor Stribiżew
    Mar 26 at 11:36











  • Thanks, That worked for me.

    – nishant
    Mar 26 at 13:47













0












0








0








I am trying to highlight a word based on the previous and next word matching with specific customer requirements.



A word should be highlighted only when previous and next word doesn't start with CAPS.



I have created regex "(?!bA-Zb)sSouls+(?!s[A-Z,0-9])" but it's also highlighting "Souls" with previous word that starts with capital.



https://regex101.com/r/wPmijX/2



In this case, "Souls" next to "Dark" should not be highlighted as it starts with caps. Only "Souls" in the second paragraph should be highlighted. Event "Souls" in the third paragraph should not be highlighted as "Game" start with capital letter.










share|improve this question














I am trying to highlight a word based on the previous and next word matching with specific customer requirements.



A word should be highlighted only when previous and next word doesn't start with CAPS.



I have created regex "(?!bA-Zb)sSouls+(?!s[A-Z,0-9])" but it's also highlighting "Souls" with previous word that starts with capital.



https://regex101.com/r/wPmijX/2



In this case, "Souls" next to "Dark" should not be highlighted as it starts with caps. Only "Souls" in the second paragraph should be highlighted. Event "Souls" in the third paragraph should not be highlighted as "Game" start with capital letter.







javascript regex regex-lookarounds






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 11:31









nishantnishant

63 bronze badges




63 bronze badges












  • You may use groups and then post-process the results, see ((?:^|b[a-z]w*)s+)(Souls)(?!s+[A-Z0-9])

    – Wiktor Stribiżew
    Mar 26 at 11:36











  • Thanks, That worked for me.

    – nishant
    Mar 26 at 13:47

















  • You may use groups and then post-process the results, see ((?:^|b[a-z]w*)s+)(Souls)(?!s+[A-Z0-9])

    – Wiktor Stribiżew
    Mar 26 at 11:36











  • Thanks, That worked for me.

    – nishant
    Mar 26 at 13:47
















You may use groups and then post-process the results, see ((?:^|b[a-z]w*)s+)(Souls)(?!s+[A-Z0-9])

– Wiktor Stribiżew
Mar 26 at 11:36





You may use groups and then post-process the results, see ((?:^|b[a-z]w*)s+)(Souls)(?!s+[A-Z0-9])

– Wiktor Stribiżew
Mar 26 at 11:36













Thanks, That worked for me.

– nishant
Mar 26 at 13:47





Thanks, That worked for me.

– nishant
Mar 26 at 13:47












2 Answers
2






active

oldest

votes


















0














Try Regex: (?<=b[a-z]w+b b)Souls(?=b [a-z]w+b)



Demo






share|improve this answer


















  • 1





    Take care that lookbehind in javascript is only supported by Chrome.

    – Toto
    Mar 26 at 12:52











  • Thanks, That worked for me in chrome browser but any other option for others browser.

    – nishant
    Mar 26 at 13:48











  • @nishant Why not use capturing groups if it should work in other browsers?

    – The fourth bird
    Mar 26 at 14:02











  • as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

    – Matt.G
    Mar 26 at 14:12











  • In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

    – nishant
    Mar 26 at 14:17


















0














If the match should be between 2 words, you could use 2 capturing groups. First capture the word before that does not start with an uppercase char and the following spaces.



Then capture Souls in a group and use a positive lookahead to assert what follows is 1+ times a space and does not start with an uppercase char.



Then you can use the captured groups in the replacement.



b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])


That will match




  • b Word boundary


  • ( Start capturing group


    • [^WA-Z]w* + Match a word char but not a capital, 0+ times a word char and 1+ times a space



  • ) Close capturing group


  • (Souls) Capture Souls in a group


  • (?= Positive lookahead to assert what follows


    • +[^WA-Z] Match 1+ times a space followed by a word char but not a capital



  • ) Close lookahead

Regex demo






const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

The Souls Game start with competent price.`;
const subst = `$1<strong>$2</strong>`;
const result = str.replace(regex, subst);

document.write(result);








share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55356108%2fregex-pattern-to-match-a-word-based-on-previous-and-next-word%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Try Regex: (?<=b[a-z]w+b b)Souls(?=b [a-z]w+b)



    Demo






    share|improve this answer


















    • 1





      Take care that lookbehind in javascript is only supported by Chrome.

      – Toto
      Mar 26 at 12:52











    • Thanks, That worked for me in chrome browser but any other option for others browser.

      – nishant
      Mar 26 at 13:48











    • @nishant Why not use capturing groups if it should work in other browsers?

      – The fourth bird
      Mar 26 at 14:02











    • as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

      – Matt.G
      Mar 26 at 14:12











    • In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

      – nishant
      Mar 26 at 14:17















    0














    Try Regex: (?<=b[a-z]w+b b)Souls(?=b [a-z]w+b)



    Demo






    share|improve this answer


















    • 1





      Take care that lookbehind in javascript is only supported by Chrome.

      – Toto
      Mar 26 at 12:52











    • Thanks, That worked for me in chrome browser but any other option for others browser.

      – nishant
      Mar 26 at 13:48











    • @nishant Why not use capturing groups if it should work in other browsers?

      – The fourth bird
      Mar 26 at 14:02











    • as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

      – Matt.G
      Mar 26 at 14:12











    • In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

      – nishant
      Mar 26 at 14:17













    0












    0








    0







    Try Regex: (?<=b[a-z]w+b b)Souls(?=b [a-z]w+b)



    Demo






    share|improve this answer













    Try Regex: (?<=b[a-z]w+b b)Souls(?=b [a-z]w+b)



    Demo







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 26 at 12:46









    Matt.GMatt.G

    2,9712 gold badges4 silver badges16 bronze badges




    2,9712 gold badges4 silver badges16 bronze badges







    • 1





      Take care that lookbehind in javascript is only supported by Chrome.

      – Toto
      Mar 26 at 12:52











    • Thanks, That worked for me in chrome browser but any other option for others browser.

      – nishant
      Mar 26 at 13:48











    • @nishant Why not use capturing groups if it should work in other browsers?

      – The fourth bird
      Mar 26 at 14:02











    • as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

      – Matt.G
      Mar 26 at 14:12











    • In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

      – nishant
      Mar 26 at 14:17












    • 1





      Take care that lookbehind in javascript is only supported by Chrome.

      – Toto
      Mar 26 at 12:52











    • Thanks, That worked for me in chrome browser but any other option for others browser.

      – nishant
      Mar 26 at 13:48











    • @nishant Why not use capturing groups if it should work in other browsers?

      – The fourth bird
      Mar 26 at 14:02











    • as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

      – Matt.G
      Mar 26 at 14:12











    • In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

      – nishant
      Mar 26 at 14:17







    1




    1





    Take care that lookbehind in javascript is only supported by Chrome.

    – Toto
    Mar 26 at 12:52





    Take care that lookbehind in javascript is only supported by Chrome.

    – Toto
    Mar 26 at 12:52













    Thanks, That worked for me in chrome browser but any other option for others browser.

    – nishant
    Mar 26 at 13:48





    Thanks, That worked for me in chrome browser but any other option for others browser.

    – nishant
    Mar 26 at 13:48













    @nishant Why not use capturing groups if it should work in other browsers?

    – The fourth bird
    Mar 26 at 14:02





    @nishant Why not use capturing groups if it should work in other browsers?

    – The fourth bird
    Mar 26 at 14:02













    as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

    – Matt.G
    Mar 26 at 14:12





    as Toto mentioned, lookbehind might not be supported in non-chrome browsers yet. (I've overlooked that possibility). you might want to consider @Thefourthbird's answer.

    – Matt.G
    Mar 26 at 14:12













    In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

    – nishant
    Mar 26 at 14:17





    In chrome, it's worked but in Firefox getting the error "SyntaxError: invalid regexp group".

    – nishant
    Mar 26 at 14:17













    0














    If the match should be between 2 words, you could use 2 capturing groups. First capture the word before that does not start with an uppercase char and the following spaces.



    Then capture Souls in a group and use a positive lookahead to assert what follows is 1+ times a space and does not start with an uppercase char.



    Then you can use the captured groups in the replacement.



    b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])


    That will match




    • b Word boundary


    • ( Start capturing group


      • [^WA-Z]w* + Match a word char but not a capital, 0+ times a word char and 1+ times a space



    • ) Close capturing group


    • (Souls) Capture Souls in a group


    • (?= Positive lookahead to assert what follows


      • +[^WA-Z] Match 1+ times a space followed by a word char but not a capital



    • ) Close lookahead

    Regex demo






    const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
    const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

    The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

    The Souls Game start with competent price.`;
    const subst = `$1<strong>$2</strong>`;
    const result = str.replace(regex, subst);

    document.write(result);








    share|improve this answer





























      0














      If the match should be between 2 words, you could use 2 capturing groups. First capture the word before that does not start with an uppercase char and the following spaces.



      Then capture Souls in a group and use a positive lookahead to assert what follows is 1+ times a space and does not start with an uppercase char.



      Then you can use the captured groups in the replacement.



      b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])


      That will match




      • b Word boundary


      • ( Start capturing group


        • [^WA-Z]w* + Match a word char but not a capital, 0+ times a word char and 1+ times a space



      • ) Close capturing group


      • (Souls) Capture Souls in a group


      • (?= Positive lookahead to assert what follows


        • +[^WA-Z] Match 1+ times a space followed by a word char but not a capital



      • ) Close lookahead

      Regex demo






      const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
      const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

      The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

      The Souls Game start with competent price.`;
      const subst = `$1<strong>$2</strong>`;
      const result = str.replace(regex, subst);

      document.write(result);








      share|improve this answer



























        0












        0








        0







        If the match should be between 2 words, you could use 2 capturing groups. First capture the word before that does not start with an uppercase char and the following spaces.



        Then capture Souls in a group and use a positive lookahead to assert what follows is 1+ times a space and does not start with an uppercase char.



        Then you can use the captured groups in the replacement.



        b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])


        That will match




        • b Word boundary


        • ( Start capturing group


          • [^WA-Z]w* + Match a word char but not a capital, 0+ times a word char and 1+ times a space



        • ) Close capturing group


        • (Souls) Capture Souls in a group


        • (?= Positive lookahead to assert what follows


          • +[^WA-Z] Match 1+ times a space followed by a word char but not a capital



        • ) Close lookahead

        Regex demo






        const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
        const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

        The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

        The Souls Game start with competent price.`;
        const subst = `$1<strong>$2</strong>`;
        const result = str.replace(regex, subst);

        document.write(result);








        share|improve this answer















        If the match should be between 2 words, you could use 2 capturing groups. First capture the word before that does not start with an uppercase char and the following spaces.



        Then capture Souls in a group and use a positive lookahead to assert what follows is 1+ times a space and does not start with an uppercase char.



        Then you can use the captured groups in the replacement.



        b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])


        That will match




        • b Word boundary


        • ( Start capturing group


          • [^WA-Z]w* + Match a word char but not a capital, 0+ times a word char and 1+ times a space



        • ) Close capturing group


        • (Souls) Capture Souls in a group


        • (?= Positive lookahead to assert what follows


          • +[^WA-Z] Match 1+ times a space followed by a word char but not a capital



        • ) Close lookahead

        Regex demo






        const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
        const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

        The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

        The Souls Game start with competent price.`;
        const subst = `$1<strong>$2</strong>`;
        const result = str.replace(regex, subst);

        document.write(result);








        const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
        const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

        The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

        The Souls Game start with competent price.`;
        const subst = `$1<strong>$2</strong>`;
        const result = str.replace(regex, subst);

        document.write(result);





        const regex = /b([^WA-Z]w* +)(Souls)(?= +[^WA-Z])/gm;
        const str = `When I finally finished Dark Souls for the first time, that feeling of struggle and triumph, of having wandered a vast and lonesome landscape, stuck with me for weeks.

        The creator of the Souls series and game director on Sekiro: Shadows Die Twice.

        The Souls Game start with competent price.`;
        const subst = `$1<strong>$2</strong>`;
        const result = str.replace(regex, subst);

        document.write(result);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 26 at 16:01

























        answered Mar 26 at 12:08









        The fourth birdThe fourth bird

        36.1k9 gold badges17 silver badges34 bronze badges




        36.1k9 gold badges17 silver badges34 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55356108%2fregex-pattern-to-match-a-word-based-on-previous-and-next-word%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript