0

I'm trying to parse a set of questions and answers that are being written to a large text field in the following format

Q1: question 1 A1: answer 1

Q2: question 2 A2: answer 2

etc...

I want the parsing to be as foolproof as possible, so I'm attempting to use regex to allow for any number of question/answer pairs (admittedly I'm an amateur when it comes to regex):

String.split('[QA][1-9]|[1-9][1-9]: ')

It's mostly working but my list items each lead with the colon and the space. Is there some reason those aren't being removed in the split?

1 Answer 1

3

That pipe (|) that you have in there is what's tripping you up. Your regex currently says (in plain language) "split the string when you find Q1 OR when you find two digits followed by a colon and a space"

The colon + space in the regex is only part of the stuff that appears to the right of your pipe.

Assuming your intention was to be able to handle things like "Q1" as well as "Q24", the bare minimum you would need to change is to make it so that your pipe only applies to the numbers

[QA]([1-9]|[1-9][1-9]):

You're still excluding 0 though, so you would stumble on "Q10", "A20" and so on.

The regex I would write here would be something like [QA]\\d+:

breaking that down

[QA]     - The first character can be either a Q or an A
  \\d    - A shorthand "character class" for [0-9], it's normally just \d, but Apex needs an extra
             backslash to signify an escape sequence
    +    - One or more of the preceding thing (in this case, a digit 0-9)
      :  - A colon followed by a space

If you want to only allow up to 99 questions, then the + could be replaced with {1,2} (quantifier operator, at least x and no more than y).

This would also hit "Q0" and "A0". You could add things into the regex to ignore those, but I think that'd be more trouble than it's worth (it'd cause the split to put the first question into index 1).

2
  • Also, using a site like regexr.com can help you build/debug regular expressions (you just need to be aware that backslashes need to be doubled in Apex, but not on that site). I have no affiliation with that site, it's just the resource that I found I like the most.
    – Derek F
    Commented Oct 19, 2021 at 15:47
  • Perfect. Thanks Derek!
    – Ben Swift
    Commented Oct 19, 2021 at 16:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .