简体   繁体   中英

Regex.Match returns different/wrong result in Unity compared to same exact code in a C# console app

I'm trying to get matches on a string in Unity using a Regular Expressions pattern. I've written the whole code inside a sample project and it worked perfectly fine.

tokens[line] = Regex.Matches(instructionLines[line], "^\\w*|(?<=q\\[)\\d*(?=\\]))";

I have validated that it matches what I need with regex101 .

I have then printed out the result in my console, which was also correct.

Console App:
 h 0
 h 1
 h 2
 h 3
 cx 1 2
 t 1

Finally, I copy-pasted the code in Unity - and it doesn't match the first word of the line like it did in the sample project.

Unity Console:
 0
 1
 2
 3
 1 2
 1

I didn't change anything, the imports are the same (using System.Text.RegularExpressions;) and the regex is correct. Why does Unity do this, and how do I fix this incorrect behaviour?

The issue was fixed thanks to @Thefourthbird, to quote from comments:

Try it adding multiline (?m)^[az] |(?<=q[)\d (?=])

In the link you added to your question regex101.com/r/FzpZXq/1 you can see at the right top that there is an m flag for multiline. As your pattern uses an anchor ^ you have to enable multiline, which can also be done using an inline modifier (?m) See regular-expressions.info/anchors.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM