A
A
Anton2017-09-10 17:08:47
Java
Anton, 2017-09-10 17:08:47

How to parse a string into multiple regexps, in the order in which they occur?

Hey!
There is a line like:

"Some string with a sequence of substrings like #123123 and [email protected]"

Where each of the words in the sentence needs to be wrapped in a specific type and put into an array in exactly the order in which they occur, for example:
[
    new Headword("Some"), 
    new PlainText("string"), 
    new PlainText("with"), 
    etc, 
    new PostalСode("123123"),  
    new Email("[email protected]")
]

It is not difficult to come up with a regular expression for each of the types, but I don’t know how to put them in the same sequence in which they occur. This is the question

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MiiNiPaa, 2017-09-10
@MiiNiPaa

Create a class that will store a regular expression that checks for a word and a type to wrap in (or a closure to wrap, or a function...).
Create as many regex-type "pairs" as you need. Put them in an array by priority (obviously PlainText should be last).
For each loop, loop through the "pairs" array. If the next regular expression comes up, create an appropriate wrapper, push it into the result array and move on to the next word.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question