sabbibJAVA sabbibJAVA - 1 year ago 51
Java Question

How to get search a string with regex, and return empty when not found

I am trying to search a string for example

Enter username:
and search for
and return anything before that. So that from the string above it would return
Enter username
, if the string was
Enter: username
or even
Enter : username
it would return
"_" being the space character.

And finally if the string was
:Enter username
then it would return an empty string

String s1 = "Enter username:";
String s2 = "Enter: username";
String s3 = ":Enter username";
Pattern p = Pattern.compile(":");
String[] expected1 = p.split(s1); //Expected return: "Enter username"
String[] expected2 = p.split(s2); //Expected return: "Enter"
String[] expected3 = p.split(s3); //Expected return: ""
//ignoring the print statement

How can I do this?

Answer Source

Here you go.

package com.client;

import java.util.*;

public class UpvoteMe {
    public static void main(String[] args) {
        List<String> list = Arrays.asList(
                "Enter username:", 
                "Enter: username", 
                ":Enter username");

        for (String s : list) {
            String[] beforeColon = s.split(":"); 
            System.out.println(s + " -> '" + beforeColon[0] + "'");



Enter username: -> 'Enter username'
Enter: username -> 'Enter'
:Enter username -> ''
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download