Regular expression to get a string between two strings in Javascript

前端 未结 11 1984
萌比男神i
萌比男神i 2020-11-21 06:29

I have found very similar posts, but I can\'t quite get my regular expression right here.

I am trying to write a regular expression which returns a string which is b

相关标签:
11条回答
  • 2020-11-21 07:15

    The chosen answer didn't work for me...hmm...

    Just add space after cow and/or before milk to trim spaces from " always gives "

    /(?<=cow ).*(?= milk)/
    

    0 讨论(0)
  • 2020-11-21 07:19

    Here's a regex which will grab what's between cow and milk (without leading/trailing space):

    srctext = "My cow always gives milk.";
    var re = /(.*cow\s+)(.*)(\s+milk.*)/;
    var newtext = srctext.replace(re, "$2");
    

    An example: http://jsfiddle.net/entropo/tkP74/

    0 讨论(0)
  • 2020-11-21 07:19
    • You need capture the .*
    • You can (but don't have to) make the .* nongreedy
    • There's really no need for the lookahead.

      > /cow(.*?)milk/i.exec('My cow always gives milk');
      ["cow always gives milk", " always gives "]
      
    0 讨论(0)
  • 2020-11-21 07:20

    The method match() searches a string for a match and returns an Array object.

    // Original string
    var str = "My cow always gives milk";
    
    // Using index [0] would return<br/>
    // "**cow always gives milk**"
    str.match(/cow(.*)milk/)**[0]**
    
    
    // Using index **[1]** would return
    // "**always gives**"
    str.match(/cow(.*)milk/)[1]
    
    0 讨论(0)
  • 2020-11-21 07:20

    Task

    Extract substring between two string (excluding this two strings)

    Solution

    let allText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum";
    let textBefore = "five centuries,";
    let textAfter = "electronic typesetting";
    var regExp = new RegExp(`(?<=${textBefore}\\s)(.+?)(?=\\s+${textAfter})`, "g");
    var results = regExp.exec(allText);
    if (results && results.length > 1) {
        console.log(results[0]);
    }
    
    0 讨论(0)
提交回复
热议问题