2

I have a use case where I would like to extract certain string from an input in scala.

My input string looks something like:

asdwf:"ssdf", as232:"ss",ABC:"xxx",sdfsf234:"sdaf"

I would like to extract the xxx after ABC.

I tried defining a regex match pattern:
val Pattern = """ABC:"(.*)",""".r, but got ABC:"xxx",sdfsf234:"sdaf" as output string.

Anything I am not doing correctly?

Thanks.

1
  • Your input string seem to have some sort of format, do you know which one? Where does it come from? Commented Apr 23, 2017 at 0:23

2 Answers 2

3

You can look for matches like this

    val p = """[^ :,"]+[\s]*:"[^"]*"""".r
    p findAllIn """asdwf:"ssdf", as232:"ss",ABC:"xxx",sdfsf234:"sdaf""""

Now you can get an iterator with all the matches.

You can extract their contents like this

    (p findAllIn """asdwf:"ssdf", as232:"ss",ABC:"xxx",sdfsf234:"sdaf"""").map(str => {
        val p(key, value) = str
        (key, value)
    }).toMap
Sign up to request clarification or add additional context in comments.

Comments

0

Try using a non-greedy expression, i.e.:

val Pattern = """ABC:"(.*?)"""".r

Update:

I'm not a scala user and I cannot test the code, but in theory the following should replace everything with the value of ABC

val res = """ asdwf:"ssdf", as232:"ss",ABC:"xxx",sdfsf234:"sdaf"""".replaceAll(""".*ABC:"(.*?)".*""", "$1")

I took a crash course on scala and the regex seems to work:

https://ideone.com/LAlCc0

2 Comments

It worked! Any way I can just extract the xxx after ABC?
@ChengXY I've update the answer, please take a look.

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.