Ankit Tater
Ankit Tater

Reputation: 619

Regular expression for extracting values after a pattern

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"]

Upvotes: 0

Views: 60

Answers (4)

YardGnomeNinja
YardGnomeNinja

Reputation: 104

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

Upvotes: 0

Yogesh Patil
Yogesh Patil

Reputation: 586

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.

Upvotes: 0

Neil Masson
Neil Masson

Reputation: 2689

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);
    }

Upvotes: 1

Pramod Karandikar
Pramod Karandikar

Reputation: 5329

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);
}

Upvotes: 0

Related Questions