找到双引号java regex之间没有被捕获的特定字符串

时间:2016-05-05 07:23:25

标签: java regex

我想找到满足两个条件的字符串(比如 x ):

  1. 匹配模式html,body { height:100%; } body { background: url("img/GProxpt.jpg") no-repeat center center fixed;; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; padding:0; margin:0; color:#f1f3f5; font-family: "Courier New"; font-size:14px; } .container-fluid { background-color: rgba(0, 0, 0, 0.6); /* position: absolute; */ /* top: 0; */ /* left: 0; */ /* width: 100%; */ height: 100%; /* overflow: auto; */ } .icon-menu { margin-top:20px; margin-right:7em; float:right; cursor:pointer; width:30px; height:40px; } .icon-menu:hover { width:35px; height:45px; } .row-menu { background:red; min-height: 100%;} .left-side { width:100%; height:100%; padding-left:20px; margin-top:7em; } .left-side .title { color:#DCEA5F; font-size:50px; } .left-side .title .sub-title { font-size:35px; } .left-side .text-par { padding-top:20px; padding-right:0; font-size:20px; } .cols { /* position: absolute; */ display: block; min-height: 100vh; margin-top: 20px; float: left; } .outer-right-side { position:relative; background:#18232E; margin-right:0; margin-top:0; } .outer-left-side { margin-bottom:0; position:relative; background:white; }
  2. 与模式\b(x)\b
  3. 不匹配

    换句话说,我正在寻找 x 的值,这是一个完整的单词(condition1),它不是双引号(condition2)。

    • ".*?(x).*?(?<!\\)"不接受
    • " x /" m":只接受第二个 x

    哪些Java代码会找到 x

1 个答案:

答案 0 :(得分:1)

第一个条件是直截了当的。要检查第二个条件,您必须检查有效双引号的数量。如果它们是偶数则在第一个条件下捕获的字符串是有效的。

if len(optionText) < 7 then
    for i=1 to 7-len(optionText)
        optionText = optionText & "&nbsp;" 
    next
end if

输出

String text = "basdf + \" asdf \\\" b\" + b + \"wer \\\"\"";
String toCapture = "b";
Pattern pattern1 = Pattern.compile("\\b" + toCapture + "\\b");
Pattern pattern2 = Pattern.compile("(?<!\\\\)\"");
Matcher m1 = pattern1.matcher(text);
Matcher m2; 
while(m1.find()){                               // if any <toCapture> found (first condition fulfilled)
    int start = m1.start();
    m2 = pattern2.matcher(text);
    int count = 0;
    while(m2.find() && m2.start() < start){     // count number of valid double quotes "
        count++;
    }
    if(count % 2 == 0) {                        // if number of valid quotes is even 
        char[] tcar = new char[text.length()];
        Arrays.fill(tcar, '-');
        tcar[start] = '^';
        System.out.println(start);
        System.out.println(text);
        System.out.println(new String(tcar));
    }
}