简体   繁体   English

使用正则表达式将字符串拆分为多个字符串

[英]Splitting a string into multiple strings using regex

I was working on a task to parse a cucumber feature string where I need to split string into 5 like the following. 我正在执行一项分析黄瓜特征字符串的任务,其中需要将字符串拆分为5,如下所示。

String data = "calls 'create' using 'POST' on some uri";

I was implementing the basic split functionality multiple times (without any regex which is very tedious) to generate the data into the following. 我多次实现了基本的拆分功能(没有任何繁琐的正则表达式)以将数据生成到以下代码中。

String dataArray[] = {"calls '","create","' using '","POST", "' on some uri"};

I wanted to obtain the names of dataArray[1] and dataArray[3] . 我想获取dataArray[1]dataArray[3] Is there a way to generate the above dataArray using regex and split or some other straight forward method? 有没有办法使用正则表达式和split或其他一些直接方法来生成上述dataArray

Here is a solution which use Regex: 这是使用正则表达式的解决方案:

public static void main (String[] args) {
  String data = "calls 'create' using 'POST' on some uri";
  String[] dataArray = new String[2];
  Matcher matcher = Pattern.compile("'[a-zA-Z]+'").matcher(data);
  int counter = 0;
  while (matcher.find()) {
    String result = matcher.group(0);
    dataArray[counter++] = result.substring(1, result.length() - 1);
  }
}

Output: 输出:

dataArray[0] --> create
dataArray[1] --> POST

Simply use this? 只需使用这个?

String dataArray[] = data.split("'");
->
[calls , create,  using , POST,  on some uri]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM