0

已经进行了大量研究,但无法找到正则表达式掩码的正确格式,以便从另一个字符串中提取字符串。

假设我有以下字符串:“The quick brown fox ABC3D97 jumps over the lazy wolf”我需要根据掩码提取“ABC3D97”:/[AZ]{3}\d{1}[AZ]{1} \d{2}/ 但我只是找不到上述正确的语法,并且它的变体返回不匹配。

我的测试代码如下:

#include <Regexp.h>

void setup ()    {
  Serial.begin (115200);

  // match state object
  MatchState ms;

  // what we are searching (the target)
  char buf [100] = "The quick brown fox ABC3D97 jumps over the lazy wolf";
  ms.Target (buf);  // set its address
  Serial.println (buf);

  char result = ms.Match ("d{3}");   <-- returns no match. 
  
  if (result > 0)    {
    Serial.print ("Found match at: ");
    int matchStart = ms.MatchStart;
    int matchLength = ms.MatchLength;
    Serial.println (matchStart);        // 16 in this case     
    Serial.print ("Match length: ");
    Serial.println (matchLength);       // 3 in this case
    String text = String(buf);
    Serial.println(text.substring(matchStart,matchStart+matchLength));
    }
  else
    Serial.println ("No match.");
    
}  // end of setup  

void loop () {}

欢迎协助。

4

1 回答 1

2

您正在使用的库似乎是来自 LUA 的 Nick Gammon 的正则表达式功能端口

LUA 的正则表达式使用与其他常用正则表达式不同的语法。该库的 README 提供了LUA 正则表达式文档的链接。

LUA 使用%而不是\用于字符类,因此\d需要写为%d. 该库也不支持{number}指定匹配数的语法。您必须重复匹配字符。

根据文档,匹配字符串应该是:

[A-Z][A-Z][A-Z]%d[A-Z]%d%d

并不是

[A-Z]{3}\d{1}[A-Z]{1}\d{2}
于 2021-09-27T00:05:41.270 回答