Jayesh Vyas
Jayesh Vyas

Reputation: 31

splits strings in java in different manner

I am very new to java. i want to splits the string into following manner. suppose i have given a string input like sample 1 jayesh =10 vyas =13 harshit=10; and so on as a input sample 2: harsh=2, vyas=5;

now i want to store jayesh, vyas, harshit from sample 1 and harsh , vyas from sample 2(all this type of strings which are just before the assignment operator) into string or char array.

so can anyone please tell me about that how to do this in java. i know about split method in java, but in this case there are multiple strings i have to store.

Upvotes: 1

Views: 101

Answers (2)

Avaneesh
Avaneesh

Reputation: 162

you can use replaceAll() to get the expected results

String stringToSearch = "jayesh =10 vyas =13 harshit=10;";  

stringToSearch = stringToSearch.replaceAll("=\\d+;?","");

System.out.println(stringToSearch);   

output:
jayesh  vyas  harshit

Upvotes: 0

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

you can use =\\d+;? regex

=\\d+;? match = and as many digits with ; as optional

    String s="jayesh =10 vyas =13 harshit=10;";
    String[] ss=s.split("=\\d+;?");
    System.out.println(Arrays.toString(ss));

output

[jayesh ,  vyas ,  harshit]

To extend it further you can use \\s*=\\d+[,;]?\\s*

\\s* : match zero or more spaces

[,;]? match any character mention in the list as optional

but if you want to avoid any special character after digits then use

\\s*=\\d+\\W*" :

\\s*= : match zero or more spaces and = character

\\d+ : match one or more digits

\W* : match zero or more non-word character except a-zA-z0-9_

    String s="harsh=2, vyas=5; vyas=5";
    String s2 ="jayesh =10 vyas=13 harshit=10;";
    String regex="\\s*=\\d+\\W*";
    String[] ss=s.split(regex);
    String[] ss2=s2.split(regex);
    System.out.println(Arrays.toString(ss));
    System.out.println(Arrays.toString(ss2));

output

[harsh, vyas, vyas]
[jayesh, vyas, harshit]

Note : Space after , is added for formatting by the Arrays.toString function though there is no space in the ss and ss2 array elements.

For Hashset use

    Set<String> mySet = new HashSet<String>(Arrays.asList(ss));

Upvotes: 4

Related Questions