I have String variable which stores a pattern/regular expression :
String var = "(?<timestamp>d+/d+/d+sd+:d+:d+.d+)s(?<filename>[a-z]+.[a-z]+:d+):s[(?<type>[A-Z]+)]:(?<text>[sS]+)";
I want to match log string of type(I have edited the fields):
2060/12/12 12:12:12.017602 abc.go:000: [INFO]:abc.cpp:00:Parsing String : 1920x1080'
I am able to match the log String successfully when I use raw String and non-raw String of the format :
String raw = r'(?<timestamp>d+/d+/d+sd+:d+:d+.d+)s(?<filename>[a-z]+.[a-z]+:d+):s[(?<type>[A-Z]+)]:(?<text>[sS]+)';
String non_raw = "(?<timestamp>\d+\/\d+\/\d+\s\d+\d+:\d+:\d+.\d+)\s(?<filename>[a-z]+.[a-z]+:\d+):\s\[(?<type>[A-Z]+)\]:(?<text>[\s\S]+)",
I have tried the following method but nothing seems to work:
String convert2NonRaw(String pattern) {
return pattern.replaceAll(r'', r'\');
}
So how do I convert my String var
to raw or non_raw format such that I could use to as an input to RegExp exp = RegExp(var);
? Is there any package that could help work it out?
2
Answers
Use this function to convert your String.
Complete Code
Output
Try On Dart Pad
As Barmar noted in a comment, this question is nonsensical. A raw string literal
r'd+'
is the same thing as a non-raw string literal'\d+'
. You cannot "convert" from one to the other; the compiler will end up creating the sameString
object in both cases.Your original string literal is essentially malformed from the start.
d
is not a recognized escape sequence in Dart, and the string literal'd'
will create the sameString
object as'd'
. Therefore it is impossible to recover and escape whatever backslashes you originally typed into your non-raw literal. You really should just use a raw string literal from the start. It’s unclear why you don’t.Based on your comment to another answer:
If you are reading the string from a file, then you shouldn’t need to do anything. Escape sequences exist for the purpose of entering string literals (because otherwise you wouldn’t be able enter certain characters). If the file you’re reading from already contains backslashes, the string you get by reading that file also will already contain those backslashes.
If that’s not the case, then you should provide a minimal example that can reproduce the actual problem you’re encountering instead of asking an XY problem about converting between raw strings and non-raw strings.