0

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.

2
  • 3
    Why do you think you need a regex? Commented 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. Commented Nov 20, 2018 at 6:14

3 Answers 3

3

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());
}
Sign up to request clarification or add additional context in comments.

6 Comments

Doesn't matter.
If this resolved your issue, please accept the answer.
@shmosel why it doesn't matter? \\d will only match a digit, right?
@Kartik I think he was referring to input.
@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
|
0

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

0

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

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.