简体   繁体   中英

find a string with regex and javascript

I am trying to match the string 6c81748b9239e96e it's random each time. Using the following code below. My problem is that it matches the entire string and I only need the random string that contains the letters and numbers.

String

<a href="playgame.aspx?gid=4&tag=6c81748b9239e96e">Play</a>

javascript regex

string.match(/\&tag\=[A-Za-z0-9]+\"\>/i);

You could use Regular Expression Groups to match, and later access the pattern you are after. The regex you will need to use is like so: /\\&tag\\=([A-Za-z0-9]+)\\"\\>/i . The round brackets ( ( and ) ) will denote the group you want to capture. You can then access the capture group as shown here .

EDIT: Upon closer inspection it seems that you might be using an incorrect regular expression. I am not really used to Javascript regexes but it seems that you are escaping the & and = and > , which is not required. Try this instead: /&tag=([A-Za-z0-9]+)\\">/i .

Here is my suggestion:

  1. Add the snippet provided by @Artem Barger to your code: https://stackoverflow.com/a/901144/851498 You need to slightly modify it, though (adding the str argument):

     function getParameterByName( name, str ) { name = name.replace(/[\\[]/, "\\\\\\[").replace(/[\\]]/, "\\\\\\]"); var regexS = "[\\\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec( str ); if(results == null) return ""; else return decodeURIComponent(results[1].replace(/\\+/g, " ")); } 
  2. Use it this way:

     var str = getParameterByName( 'tag', string ); 

Jsfiddle demo: http://jsfiddle.net/Ralt/u9MAv/

var myregexp = /(&tag=)([A-Za-z0-9]+)\b/img;
var match = myregexp.exec(subject);
while (match != null) {
    for (var i = 0; i < match.length; i++) {
        // matched text: match[i]
    }
    match = myregexp.exec(subject);
}

Your regex

&tag=([A-Za-z\d]+)"

It's simplified (you escaped too much) and parenthesis were added to put the thing you want in group 1

In javascript this becomes

var myregexp = /&tag=([A-Za-z\d]+)"/;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1];
} else {
    result = "";
}

Explanation

Match the characters “&tag=” literally «&tag=»
Match the regular expression below and capture its match into backreference number 1 «([A-Za-z\d]+)»
   Match a single character present in the list below «[A-Za-z\d]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      A character in the range between “A” and “Z” «A-Z»
      A character in the range between “a” and “z” «a-z»
      A single digit 0..9 «\d»
Match the character “"” literally «"»

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM