# regex to find \n within quotes and not ones outside quotes

For example,

string = "ads, 32, dv, \"sdf\"
sd, 213, as, \"asd
asd\"
asd, 123 sd, \"asd\"";


There are 3 line returns \n. I want to find the second one since it is inside the quotes ("").

StringCases[string,RegularExpression["put regular expression here"]];


I have tried the following regex which should work if only Mathematica would allow variable length lookbehind assertions:

RegularExpression["(?<=,\"[^\"]*)\\n(?=[^\"]*\",)"]

• routes = quotes? Can you give Mathematica code to create the string you're actually providing in the question? Without that, it's ambiguous. – Jens Jul 1 '17 at 16:23
• i have updated the code. – user13892 Jul 1 '17 at 16:35
• Sorry, I just saw now that i misspelled the word quote in the title. – user13892 Jul 1 '17 at 19:38

You are able to reference the parenthesised sections of your RegularExpression on the right-hand side with RuleDelayed.

With

string = "ads, 32, dv, \"sdf\"
sd, 213, as, \"asd
asd\"
asd, 123 sd, \"asd\"";


Then

StringCases[
string,
RegularExpression["\"([^\"]+?\n[^\"]+?)\""] :> "$1" ]  {"asd asd"}  Hope this helps. • A false match is found in the string "1,\"abc\",3\n4,\"def\",6\n". – WReach Jul 2 '17 at 4:53 • @WReach It returns {",3\n4,"} as expected (with Mathematica 8.0.4). – Alexey Popkov Jul 2 '17 at 9:46 • @Edmund Actually Rule works here as well as RuleDelayed. – Alexey Popkov Jul 2 '17 at 9:46 • @AlexeyPopkov I was assuming that the usual rules for matching quotes were to be respected (e.g. like in CSV parsing). Under that assumption, I expect no matches from my example. Perhaps the OP can clarify whether quote matching is a requirement. – WReach Jul 2 '17 at 14:08 • @WReach Thanks, added a special note to my answer. – Alexey Popkov Jul 2 '17 at 14:22 Here is a solution which won't include the outer quotes in the matched string and hence will count every quote twice: StringCases["a\"b\nc\"d\ne\"", RegularExpression["(?<=\")[^\"]+?\n[^\"]+?(?=\")"]]  {"b\nc", "d\ne"}  Compare to Edmund's solution: StringCases["a\"b\nc\"d\ne\"", RegularExpression["\"([^\"]+?\n[^\"]+?)\""] :> "$1"]

{"b\nc"}


Note that both solutions use + instead of * since you wish to find only the second \n what contradicts the title of the question: "regex to find \n within quotes and not ones outside quotes". Based on the title only, the solution would use * in order to allow matching lonely newline character inside of the quotes:

StringCases[string, RegularExpression["(?<=\")[^\"]*?\n[^\"]*?(?=\")"]]

{"\n  sd, 213, as, ", "asd\n  asd", "\n  asd, 123 sd, "}


It is worth to add also that both mine and Edmund's solution completely ignore the usual rules for matching quotes as WReach correctly notes in the comment. If quote matching is required, one should apply approaches shown in the following threads: