简体   繁体   中英

Javascript Regex doesn't match with my String

I have the following String :

var resultLine= "[UT] - GSM incoming call : STEP 1 - Simulate reception from server (1)Rerun3713 msAssertion ok"

And the following code which is responsible to check of the String matched with the Regex :

var resultRE = /^([ \w-]*: )?(.+) \((\d+), (\d+), (\d+)\)Rerun/;
var resultMatch = resultLine.match(resultRE);
if (resultMatch) {
   return true;
} else {
   return false;
}

In this case, i have an error in my Regex because i always get "false". Where is my mistake ?

This matches nothing in your string

([ \w-]*: )?

Since it was optional, that doesn't matter because it gets caught by the all inclusive

(.+)

If you were trying to match the [UT] part with it's separator, it would look something like this

(\[\w+\][\s\-]*)?

As noted in the comments, you only have one number in parentheses but your regex requires three sets of them, separated by commas. This will allow any number of numbers, separated by commas indefinitely (I don't know if there's a limit or not).

\((\d+,\s)*(\d+)\)

If you need something more specific, you'll have to be more specific about what template your matching, not a specific case. But the best I can figure with what you've provided is

^(\[\w\][\s\-]*)?(.+)\((\d+,\w)*(\d+)\)Rerun

I would recommend the following pattern based on what it appears you are looking for:

var resultRE = /^([\\[ \\w\\]-]*: )(.+) \\(([0-9, ]*)\\)Rerun(.*)$/

This should force all capture groups to exist, even if they are empty, and will allow for multiple numbers before Rerun as you seem to expect.

var resultRE = /\((\d+)(?:, (\d+))?(?:, (\d+))?\)Rerun/;
if (resultRE.test(resultLine)) {
  var num1 = RegExp.$1,
  num2 = RegExp.$2,
  num3 = RegExp.$3;
}

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