码迷,mamicode.com
首页 > 编程语言 > 详细

Java如何拆分正则表达式和字符串?

时间:2018-09-10 11:17:50      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:imp   shel   tor   ssi   tool   结果   cti   ati   regex   

在Java编程中,如何拆分正则表达式和字符串?

以下示例演示如何使用regex.Pattern类的Pattern.compile()方法和patternname.split()方法拆分正则表达式。

package com.yiibai;

import java.util.regex.Pattern;

public class SplittingRegularExpression {
   public static void main(String args[]) {
      Pattern p = Pattern.compile(" ");
      String tmp = "this is the Java example";
      String[] tokens = p.split(tmp);

      for (int i = 0; i < tokens.length; i++) {
         System.out.println(tokens[i]);
      }
   }
}
Java

上述代码示例将产生以下结果 -

this
is
the
Java
example
Shell

示例-2

以下是如何拆分正则表达式的另一个示例。

package com.yiibai;

import java.util.regex.Pattern;

public class SplittingRegularExpression2 {
    public static void main(String a[]) {
        String s1 = "Learn how to use regular expression in Java programming. Here are most commonly used example";
        Pattern p1 = Pattern.compile("(to|Java|in|are|used)");
        String[] parts = p1.split(s1);

        for (String p : parts) {
            System.out.println(p);
        }
    }
}
Java

上述代码示例将产生以下结果 -

Learn how 
 use regular expression 

 programm
g. Here 
 most commonly 
 example

Java如何拆分正则表达式和字符串?

标签:imp   shel   tor   ssi   tool   结果   cti   ati   regex   

原文地址:https://www.cnblogs.com/borter/p/9617155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!