在正则表达式中悬空元字符+来检测GaussianRational

时间:2015-10-02 10:26:59

标签: java regex

public GaussianRational read()  
{
    Scanner s = new Scanner(System.in);     // associate Scanner object with standard input stream
    Long p,q,m,n; 
    s.findWithinHorizon("(-?\\d+)\\s*/\\s*(-?\\d+)\\s*(\\+? \\s* -?\\d+)\\s*/\\s*(-?\\d+\\s*i)",0);// scan standard input for regular expression pattern

    MatchResult result = s.match();           // collect subtrings matched by "capturing groups" in the pattern (in parentheses)
    s.close();                                // scanner no longer needed
    p = Long.parseLong(result.group(1));     
    q = Long.parseLong(result.group(2));   
    m = Long.parseLong(result.group(3));     
    n = Long.parseLong(result.group(4));     
    System.out.print(p);
    return new GaussianRational(p,q,m,n);
}

我正在尝试使用下面的正则表达式从<{1}}输入中解析4个长数字

GaussianRational

但我一直在异常悬空(-?\\d+)\\s*/\\s*(-?\\d+) \\s*(+?)\\s* (-?\\d+)\\s*/\\s*(-?\\d+\\s*i) 或悬空+在表达式中间使用

谢谢!

2 个答案:

答案 0 :(得分:0)

您忘记在draw_networkx_edge_labels(G, pos, edge_labels=None, label_pos=0.5, font_size=10, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0, bbox=None, ax=None, rotate=True, **kwds) 之前添加.。没有点+?就没有意义,因为它没有被转义。

+

如果你的意思是加号。

"(-?\\d+)\\s*/\\s*(-?\\d+)\\s*(.+?)\\s*(-?\\d+)\\s*/\\s*(-?\\d+)\\s*i"

答案 1 :(得分:0)

您需要转义加号并将最后一个捕获组边界移动到数字:

Long p,q,m,n; 
s.findWithinHorizon("(-?\\d+)\\s*/\\s*(-?\\d+)\\s*(\\+?)\\s*(-?\\d+)\\s*/\\s*(-?\\d+)\\s*i",0);
//                                                                                  ^
MatchResult result = s.match();           // collect subtrings matched by "capturing groups" in the pattern (in parentheses)
s.close();                                // scanner no longer needed
p = Long.parseLong(result.group(1));     
q = Long.parseLong(result.group(2));   
m = Long.parseLong(result.group(4));     
n = Long.parseLong(result.group(5));     
 // With "1/2+3/4 i" as input, the results are
System.out.println(p); // => 1
System.out.println(q); // => 2
System.out.println(m); // => 3
System.out.println(n); // => 4

请参阅IDEONE demo