开发者

What is the mistake in if(this.id.match(/^None_+\d+_+\d+$/))

开发者 https://www.devze.com 2023-03-15 11:51 出处:网络
Hi I have written one Regular expression to match the pattern like \"开发者_开发技巧None_123_234\"

Hi I have written one Regular expression to match the pattern like

"开发者_开发技巧None_123_234"  

Below is my code

if(this.id.match(/^None_+\d+_+\d+$/))  

But it is not working. Can we write it in any other way? Please someone help me.


It's not working, because it won't match against:

"None_123_234"

That is because of the caret ^, which will assert that the match is done from the beginning of the string. The beginning of the string in this case is the double quote ". Furthermore, the dollar sign $ will assert that the pattern continues until the end of the string. The end of the string in this case is again the double quote ".

This is the exact explanation of the regex (/^None_+\d+_+\d+$/) you are giving:

  1. Assert position at the beginning of the string «^»
  2. Match the characters “None” literally «None»
  3. Match the character “_” literally «_+»

    a. Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

  4. Match a single digit 0..9 «\d+»

    a. Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

  5. Match the character “_” literally «_+»

    a. Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

  6. Match a single digit 0..9 «\d+»

    a. Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

  7. Assert position at the end of the string (or before the line break at the end of the string, if any) «$»

You have two options:

  1. Either your string should not start with anything else other than None_...
  2. OR, you should change your regex to match that pattern anywhere in the text, like this:
if(this.id.match(/None_+\d+_+\d+/))


It's hard to say what the problem is just from the code you've given, but my guess is that it's got nothing to do with the regex.

The regex itself looks fine to match against None_123_234.

My guess is that you have a problem with this.id. As I say, it's hard to be sure without seeing more of your code, because we don't know what this looks like in the context of the one line of code you've given us.

However, I'm taking the fact that you've put jquery in your tags as a clue, because the code you've given us has no JQuery in it at all.

If the this is a DOM element, then it will have a .id property. However, if it's a JQuery element, then it won't -- this.id will be undefined.

If that's the case, you can use the JQuery .attr() method to get the ID instead, like so:

if(this.attr('id').match(/^None_+\d+_+\d+$/))  

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消