Sunday 15 March 2020

Regex: Lookahead and Lookbehind: Split a string by keeping delimiters

Using Lookahead and Lookbehind operators, we can split the string by keeping delimiters.

Following table summarizes lookahead and lookbehind operators.

Operator
Example
Description
Lookahead
(?=foo)
Asserts that what immediately follows the current position in the string is foo
Lookbehind
(?<=foo)
Asserts that what immediately precedes the current position in the string is foo

App.java
package com.sample.app;

import java.util.Arrays;

public class App {

 private static String[] splitByDelimiterUsingLookBehind(String str, String delimiter) {
  return str.split("(?<=" + delimiter + ")");
 }

 private static String[] splitByDelimiterUsingLookAhead(String str, String delimiter) {
  return str.split("(?=" + delimiter + ")");
 }

 private static void printArray(String[] str) {
  System.out.println(Arrays.toString(str));
 }

 public static void main(String args[]) throws InterruptedException {
  String[] result = splitByDelimiterUsingLookAhead("a#b#c#d", "#");
  printArray(result);

  result = splitByDelimiterUsingLookBehind("a#b#c#d", "#");
  printArray(result);
 }

}

Output
[a, #b, #c, #d]
[a#, b#, c#, d]



Previous                                                    Next                                                    Home

No comments:

Post a Comment