如何匹配具有直接特殊字符的行中的字符串?

时间:2016-09-26 11:41:15

标签: java regex string contains

我已经给出了一个像下面这样的条件,它无法匹配from table1;insert into table1(col1,col2 ..)

这样的行
if(Arrays.asList(line.split("\"")).contains("table1")) || 
        Arrays.asList(line.split(" ")).contains("table1"))
    System.out.println(line); 

我需要遵循哪种逻辑?

6 个答案:

答案 0 :(得分:1)

使用正则表达式并将所需的所有特殊字符放在该表达式中。

<statement-card>
    <statement-card-title>
        <div class="schedule-statement-title">Payment schedule</div>
    </statement-card-title>
    <statement-card-summary>
        <h4 class="statement-card-section-title">Payment frequency:</h4>
        <div>
            {{frequency}}
        </div>
        <div>
            Next payment: {{payment?.scheduledDate | date:'MMMM dd, yyyy'}}
        </div>
    </statement-card-summary>
    <statement-card-addition>
        <h4 class="statement-card-section-title">Payment amount:</h4>
        <div class="addition-line"><span>Amount</span><span>{{payment?.amount}}</span></div>
        <div class="addition-line"><span>Sales tax</span><span>{{payment?.salesTax}}</span></div>
        <hr class="addition-seperator" />
        <div class="addition-total"><span>Total</span><span>{{getPaymentTotal()}}</span></div>
    </statement-card-addition>
    <statement-card-payment-method>
        <h4 class="statement-card-section-title">Payment method:</h4>
        <img src="images/bank.png" width="48" height="48" class="payment-method-icon" />
        <div class="payment-method-summary">
            <div>Bank</div>
            <div>Account ending in  ••••••••••1234</div>
        </div>
    </statement-card-payment-method>
    <statement-card-interactions>
        <div class="row">
            <div class="col-md-6">
                <a href="#" class="pull-right">MAKE A PAYMENT</a>
            </div>
            <div class="col-md-6">
                <a href="#" class="pull-right">VIEW PAYMENT SCHEDULE</a>
            </div>
        </div>
    </statement-card-interactions>
</statement-card>

答案 1 :(得分:0)

使用正则表达式匹配,如下所示

foreach

请注意,您可以在方括号中放置要分割线条的任何字符。

答案 2 :(得分:0)

试试这个:

if (Arrays.asList(list.split("[^a-zA-Z0-9_]")).contains("table1")) {
        System.out.println(list);
}

或者,因为RealSkeptic建议使用正则表达式匹配:

if (list.matches(".*\\btable1\\b.*")) {
        System.out.println(list);
}

答案 3 :(得分:0)

您可以使用正则表达式:

    Pattern pat = Pattern.compile("(?<!\\p{L})table1(?!\\p{L})");
    if (pat.matcher(line).find())
    {
      System.out.println(line);
    }

答案 4 :(得分:0)

如果我理解你的问题,你可以在不使用Splits的情况下实现它:

 String stringPattern = ".*table1.*";
 Pattern pattern = Pattern.compile(stringPattern);
 Matcher matcher = pattern.matcher(line);
 if (matcher.matches())
  System.out.println(line); 

答案 5 :(得分:0)

您可以使用带有负面外观和负面外观的正则表达式:

String input = "from table1;";
Pattern p = Pattern.compile("(?<![a-zA-Z0-9_])table1(?![a-zA-Z0-9_])");
Matcher matcher = p.matcher(input);

if (matcher.find()) 
    System.out.println(input);

这将匹配任何"table1"出现的任何字母,数字或_符号之前或之后的出现。