Javascript Regexp - Match Characters after a certain phrase

后端 未结 5 435
名媛妹妹
名媛妹妹 2020-12-13 03:36

I was wondering how to use a regexp to match a phrase that comes after a certain match. Like:

var phrase = \"yesthisismyphrase=thisiswhatIwantmatched\";
var          


        
相关标签:
5条回答
  • 2020-12-13 04:16

    You use capture groups (denoted by parenthesis).

    When you execute the regex via match or exec function, the return an array consisting of the substrings captured by capture groups. You can then access what got captured via that array. E.g.:

    var phrase = "yesthisismyphrase=thisiswhatIwantmatched"; 
    var myRegexp = /phrase=(.*)/;
    var match = myRegexp.exec(phrase);
    alert(match[1]);
    

    or

    var arr = phrase.match(/phrase=(.*)/);
    if (arr != null) { // Did it match?
        alert(arr[1]);
    }
    
    0 讨论(0)
  • 2020-12-13 04:27

    It is not so hard, Just assume your context is :

    const context = https://medicoads.net/pa/GIx89GdmkABJEAAA+AAAA
    

    And we wanna have the pattern after pa/, so use this code:

    const pattern = context.match(/pa\/(.*)/)[1];
    

    The first item include pa/, but for the grouping second item is without pa/, you can use each what you want.

    0 讨论(0)
  • 2020-12-13 04:30
    phrase.match(/phrase=(.*)/)[1]
    

    returns

    "thisiswhatIwantmatched"
    

    The brackets specify a so-called capture group. Contents of capture groups get put into the resulting array, starting from 1 (0 is the whole match).

    0 讨论(0)
  • 2020-12-13 04:33

    Let try this, I hope it work

    var p = /\b([\w|\W]+)\1+(\=)([\w|\W]+)\1+\b/;
    console.log(p.test('case1 or AA=AA ilkjoi'));
    console.log(p.test('case2 or AA=AB'));
    console.log(p.test('case3 or 12=14'));

    0 讨论(0)
  • 2020-12-13 04:37

    If you want to get value after the regex excluding the test phrase, use this: /(?:phrase=)(.*)/

    the result will be

    0: "phrase=thisiswhatIwantmatched" //full match
    1: "thisiswhatIwantmatched" //matching group
    
    0 讨论(0)
提交回复
热议问题