Java中使用正则表达式分割字符串

在参数中传递正则表达式(Regex)时拆分字符串,单个字符串将基于(Regex)进行拆分,因此,我们可以将字符串存储在字符串数组中。在本文中,我们将学习如何根据给定的正则表达式分割字符串。

首先,我们对给定的 String 应用String.split()并在参数中传递给定的正则表达式。它将返回一个字符串数组,我们将其存储在数组中,然后打印该数组。

// java program to split a string. 

import java.io.*; 

class GFG { 
    public static void main(String[] args) 
    { 
        
// give String 
        String s1 =
"hello-from-sample"

        
// given regex 
        String regex =
"-"

        
// apply split() method on the given string and pass 
        
// regex in the argument. 

        String[] split 
            = s1.split(regex);
// return an array of strings 

        
// printing output 
        for (String s : split) { 
            System.out.print(s +
" "); 
        } 
    } 
}

上述程序的解释:

  1. 将任何类型的正则表达式(它是单个字符或字符串)传递给 split() 方法,该方法将返回字符串数组并替换元素。
  2. 但是,如果您尝试使用一些特殊字符(例如 * 或 / )拆分 String 这是正则表达式中预定义的字符。
  3. 所以它不起作用,所以你需要以这种形式传递正则表达式[//*]
  4. 这里需要使用反斜杠(//),方括号代表具体字符。