Amit
Amit

Reputation: 233

How to retrieve specific value from String in java

I have a String field which contains value :

 String a = "Local/5028@from-queue-bd7f,1";

Now As per my need i need value '5028' extracted from the above String field.

Upvotes: 0

Views: 1859

Answers (6)

vishal_aim
vishal_aim

Reputation: 7854

if your string format is fixed, you can use:

String a = "Local/5028@from-queue-bd7f,1";
a = a.substring(a.indexOf('/') + 1, a.indexOf('@'));
System.out.println(a);

Upvotes: 0

PermGenError
PermGenError

Reputation: 46428

Using REGEX:

 String a = "Local/5028@from-queue-bd7f,1";
         Pattern p = Pattern.compile("\\d+");
         Matcher m = p.matcher(a);
         System.out.println(m.find() + " " + m.group());

Using String.Split:

String a = "Local/5028@from-queue-bd7f,1";
         String[] split = a.split("/");
         System.out.println(split[1].split("@")[0]);

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114797

This splits the string on each / and @.

String a = "Local/5028@from-queue-bd7f,1";
System.out.println(a.split("[/@]")[1]);

Upvotes: 3

Abhishek_Mishra
Abhishek_Mishra

Reputation: 4621

If this string is always in the given format then you can try this :

String temp=a.split("@")[0];
System.out.println(temp.substring(temp.length()-4,temp.length()));

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41220

Use String#substring function to retrieve the value. You need to pass beginning and ending index as a parameter.

String a = "Local/5028@from-queue-bd7f,1";
System.out.println(a.substring(a.indexOf('/')+1, a.indexOf('@')));

Upvotes: 1

AbhinavRanjan
AbhinavRanjan

Reputation: 1646

If you know that your format is consistent then you can either use substring method or you can split the string using / and @, and then take the second value from the tokens array.

Upvotes: 0

Related Questions