1

I am trying to capture following word, number:

stxt:usa,city:14

I can capture usa and 14 using:

stxt:(.*?),city:(\d.*)$

However, when text is;

stxt:usa 

The regex did not work. I tried to apply or condition using | but it did not work.

stxt:(.*?),|city:(\d.*)$
6
  • 2
    Maybe ^stxt:(.*?)(?:,city:(\d.*))?$? Or do you want to also support city:14 like strings with the same pattern? Split with a comma, and then with :, it will be easier. Commented Sep 6, 2016 at 14:40
  • This format of data might be better handled with some split, see also google.github.io/guava/releases/19.0/api/docs/com/google/common/… Commented Sep 6, 2016 at 14:43
  • @WiktorStribiżew yes, I want to support individual query both city and stxt. The regex you provided works for stxt but I am not able to understand it! Commented Sep 6, 2016 at 14:44
  • 1
    Well, you may also use (stxt|city):([^,]+) regex. Commented Sep 6, 2016 at 14:46
  • @WiktorStribiżew works fine. thanks ! Commented Sep 6, 2016 at 14:52

2 Answers 2

8

You may use

(stxt|city):([^,]+)

See the regex demo (note the \n added only for the sake of the demo, you do not need it in real life).

Pattern details:

  • (stxt|city) - either a stxt or city substrings (you may add \b before the ( to only match a whole word) (Group 1)
  • : - a colon
  • ([^,]+) - 1 or more characters other than a comma (Group 2).

Java demo:

String s = "stxt:usa,city:14";
Pattern pattern = Pattern.compile("(stxt|city):([^,]+)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Looking at your string, you could also find the word/digits after the colon.

:(\w+)

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.