0

How do i write a regular expression in Java which given a certain pattern, extracts the value after it and stores it in an array. If there is no value in after that pattern it should add a blank (i.e "") to the array.

As an example for pattern &&, I should get the following inputs and outputs:

  input=&&&&&&&&&&
  o/p=["","","",""];

  input=&&A&&123&&B&&985
  o/p=["A",123,B,985];
  input=&& && &&A&&488
  o/p=["","","A","488"]
1

4 Answers 4

1

You can set the delimiter on a Scanner and then iterate through its values.

    public String[] getTokens() {   
        LinkedList<String> list = new LinkedList<String>();         
        Scanner s = new Scanner(input).useDelimiter("\\&\\&");
        while(s.hasNext()) {
            list.add(s.next());
        }
        String[] a = new String[list.size()];
        return list.toArray(a);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You can try using split. You can omit the first result and use the rest from the output of the following code.

String testStr = "&&A&&123&&B&&985";
String[] splitString = testStr.split("(&&)");
for (String token : splitString) {
    System.out.println(token);
}

1 Comment

if there is nothing between&&&& i need a blank value
0
public static void main (String[] args) {
    String str = "&&A&&&&&&D&&123&&XX&&";
    String delimiters = "([&]{2})";

    // analyzing the string
    String[] tokensVal = str.split (delimiters);

    System.out.print ("[");
    for (String token: tokensVal) {
        // Print empty and space tokens
        if(token.isEmpty () || token.equals (" ")){
            System.out.print ("\"\",");
        } else {
            System.out.print (token + ",");
        }
    }
    System.out.print ("]");
}

O/P ["",A,"",D,]

There is one problem is here when there is only & in whole string eg "&&&&&&" then you have to handle it in special way.

Comments

0

I apologize that I don't know Java, but assuming it has the ability to replace and capture, you could do this in two steps.

First would be to replace any occurrence of

&&  

with

&&\s

Second would be to iterate through the captured results returned from

&{2}([^&]+)

and trim the excess space off any results

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.