I have a string as a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11.
I want to create a program such that if I give value as a then it should return a#1, If I give b then it should return b#2 from given string. I am very new to java regular expressions.
-
3Why do you think you need a regex?ernest_k– ernest_k2018-11-20 06:06:25 +00:00Commented Nov 20, 2018 at 6:06
-
Here a#1 denotes key and value. If I use split on "-" then I will get one array,again I will have to iterate that array and call split on "#". I want to reduce loops, so that at once I can get a#1 and then call split() to get key and value.Ravitosh Khatri– Ravitosh Khatri2018-11-20 06:14:55 +00:00Commented Nov 20, 2018 at 6:14
Add a comment
|
3 Answers
Yes, a simple regex should do the trick. Just prepend your input to a regex matching # followed by some numbers (assuming that's the pattern):
String str = "a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11";
String input = "a";
Matcher m = Pattern.compile(input + "#\\d+").matcher(str);
if (m.find()) {
System.out.println(m.group());
}
6 Comments
shmosel
Doesn't matter.
shmosel
If this resolved your issue, please accept the answer.
Kartik
@shmosel why it doesn't matter?
\\d will only match a digit, right?shmosel
@Kartik I think he was referring to
input.Kartik
@shmosel in his comment on the question, he talks about key-value, so I think by value he means the digit.. but OP should confirm that
|
Probably using RegExpo for such simple task is overhead. Just string search:
public static String get(char ch) {
final String str = "a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11";
int pos = str.indexOf(ch);
if (pos < 0)
return null;
int end = str.indexOf('-', pos);
return end < 0 ? str.substring(pos) : str.substring(pos, end);
}
Comments
Not better than @shmosel's answer, but if you need to repeatedly extract values, you can build a Map once, then each retrieval will be faster (but initial Map construction will be slow):-
Map<String, String> map = Arrays.stream(str.split("-"))
.collect(Collectors.toMap(o -> o.substring(0, o.indexOf('#')).trim(), Function.identity()));
Here's the full code:-
String str = "a#1-b#2-c#3-d#4-e#5-f#6-g#7-h#8-i#9-j#0-k#10-l#11";
Map<String, String> map = Arrays.stream(str.split("-"))
.collect(Collectors.toMap(o -> o.substring(0, o.indexOf('#')).trim(), Function.identity()));
System.out.println(map.get("a"));
Output: a#1