Home > Enterprise >  Regular Expression - Not Matching Full Text/Replacing Other Parts
Regular Expression - Not Matching Full Text/Replacing Other Parts

Time:10-19

I have a quiz that looks similar to the following:

1: How old am I?
A: 8 days
B: 75
C: 100
D: 99correct
xxxxxxxxxxxx
2: What is your favorite color?
A: blue
B: greencorrect
C: red
D: blue
xxxxxxxxxxxx

In each case, the correct answer is marked by using the word correct at the end of the correct answer.

What I want to do is to take that correct answer and add it after the xxxxxxxxxxxx, so that it reads:

xxxxxxxxxxxx B: Green.

I am currently using the following regex within Textpad in order to find the correct answer

FIND:     ([A-D]:(?s).*correct(?s).*xxxxxxxxxxxx)
REPLACE:  \1xxxxxxxxxxxx

Unfortunately, it is not working as it is replacing the whole quiz with the whole quiz and then adding xxxxxxxxxxx

But the main question, is how do I replace text that is not actually specified as the 'find text'?

Thank you.

PS. Two answers seem to have missed this, so is probably my fault that this is not clarified:

It shouldn't be adding an extra xxxxxxxxxxxx before the answer, but copying the line eg. B: greencorrect after the final xxxxxxxxxxxx for that question.

Here is sample output for the above example:

1: How old am I?
A: 8 days
B: 75
C: 100
D: 99correct
xxxxxxxxxxxx D: 99
2: What is your favorite color?
A: blue
B: greencorrect
C: red
D: blue
xxxxxxxxxxxx B: green

Obviously, the correct answer could be A,B,C or D.

CodePudding user response:

You can use

(?m)^([A-D]:.*?)correct$((?:\n.*)*?\nx{3,})

See the regex demo. The replacement pattern should be \1\2 \1.

Details:

  • (?m) - a multiline inline modifier (might be redundant in a text editor)
  • ^ - start of a line
  • ([A-D]:.*?) - Group 1: A, B, C or D, then a : and then any zero or more chars other than line break chars as few as possible
  • correct - a correct word
  • ((?:\n.*)*?\nx{3,}) - Group 2:
    • (?:\n.*)*? - zero or more lines, but as few as possible
    • \n - a newline char
    • x{3,} - three or more x chars.

CodePudding user response:

I've never worked with Textpad in particular, but in Sublime Text 3 you might want to do something like this:

FIND:      ^([A-D]:\s\S.*?)correct$
REPLACE:   xxxxxxxxxxxx $1.

It's going to turn your example into:

<...>
xxxxxxxxxxxx D: 99.
<...>
xxxxxxxxxxxx B: green.
<...>

Note that since I use ^ and $ (the beginning and the end of a line), if your editor asks you to enable multi-line mode, try to enable it if this doesn't work for you with default mode.

CodePudding user response:

Try this Find: ([A-D]:[\w ]*correct)
Replace: xxxxxxxxxxxx \1

Outputs:

1: How old am I?
A: 8 days
B: 75
C: 100
xxxxxxxxxxxx D: 99correct
xxxxxxxxxxxx
2: What is your favorite color?
A: blue
xxxxxxxxxxxx B: greencorrect
C: red
D: blue
xxxxxxxxxxxx

Regex101 Demo

Tell me if its not working for you...

  • Related