2016-11-18 107 views
-1

我想要检测何时用户输入“lw 2,3(9)”,但它不能读取括号,我使用此代码,但它仍然没有检测到括号。如何使用正则表达式正则表达式组装lw/sw指令?

{ R"((\w+) ([[:digit:]]+), ([[:digit:]]+) (\\([[:digit:]]+\\)))"} 

有人可以帮忙吗?

+1

这里有一个潜在的假设,你正在处理的汇编语言是一种常规语言。你有证据吗?如果没有,你可能会使用错误的工具, – EJP

+0

如果这应该是一些半聪明的解析器(比如IDE高亮),你应该在'\ s +'和/或'\ s *'处去找用户可以输入某种空间,例如'lw 6,5(2)'。 (但这仍然只是黑客解决方案,完整的解析器会更好) – Ped7g

回答

0
R"((\w+) (\d+), (\d+)(\(\d+\)))" 

工作对我来说

+0

为什么在括号内使用'\ d'? '\ d' ='[[:digit:]]'。 –

+0

对于“任何数字”[0-9],它看起来更简单 – cokceken

+1

是的,'[[:digit:]]'='\ d',你不必写'[\ d]'。其实,你的答案和我一样,但没有任何解释。 –

3

你必须要小心的格局过多的空间,因为你使用的是原始字符串字面,你不应该加倍转义特殊字符:

R"((\w+) ([[:digit:]]+), ([[:digit:]]+)(\([[:digit:]]+\)))" 
             ^^^   ^^^ 

这可能是更换字面是个好主意空格与[[:space:]]+

C++ demo打印lw 2, 3(9)

#include <iostream> 
#include <regex> 
#include <string> 
using namespace std; 

int main() { 
    regex rx(R"((\w+) ([[:digit:]]+), ([[:digit:]]+)(\([[:digit:]]+\)))"); 
    string s("Text lw 2, 3(9) here"); 
    smatch m; 
    if (regex_search(s, m, rx)) { 
     std::cout << m[0] << std::endl; 
    } 
    return 0; 
} 
0

既然你没有指定是否要捕捉的东西或者不是,我将提供两个片段。

您没有逃脱与原字符串文字字符,但你必须以逃避被俘组

#include <iostream> 
#include <string> 
#include <regex> 

int main() 
{ 
    std::string str = "lw 2, 3(9)"; 

    { 
     std::regex my_regex(R"(\w+ \d+, \d+\(\d+\))"); 
     if (std::regex_search(str, my_regex)) { 
      std::cout << "Detected\n"; 
     } 
    } 

    { 
     // With capture groups 
     std::regex my_regex(R"((\w+) (\d+), (\d+)(\(\d+\)))"); 
     std::smatch match; 
     if (std::regex_search(str, match, my_regex)) { 
      std::cout << match[0] << std::endl; 
     } 
    } 
} 

Live example

的额外改进可以处理多个间距(如果被允许在你的特定情况下)与\s+

我不禁注意到EJP's concerns也可能是点亮的:这是一个非常脆弱的解析解决方案。