Regex for string between 2 strings c# - regex

I'm trying to get the message string out from this VMG file. I only want to strings after the Date line and before "END:VBODY"
The best I got so far is this regex string BEGIN:VBODY([^\n]*\n+)+END:VBODY
Anyone can help refine it?
N:
TEL:+65123345
END:VCARD
BEGIN:VENV
BEGIN:VBODY
Date:8/11/2013 11:59:00 PM
thi is a test message
Hello this is a test message on line 2
END:VBODY
END:VENV
END:VENV
END:VMSG

If you want to use regex, you can modify your current regex a little, because the $0 group has what you are looking for.
BEGIN:VBODY\n?((?:[^\n]*\n+)+?)END:VBODY
Basically what happened was ([^\n]*\n+)+ turned into (?:[^\n]*\n+)+? (turning this part lazy might be safer)
And then wrap that whole part around parens: ((?[^\n]*\n+)+?)
I added \n? before this to make the output a little cleaner.
A non-regex solution might be something like this:
string str = #"N:
TEL:+65123345
END:VCARD
BEGIN:VENV
BEGIN:VBODY
Date:8/11/2013 11:59:00 PM
thi is a test message
Hello this is a test message on line 2
END:VBODY
END:VENV
END:VENV
END:VMSG";
int startId = str.IndexOf("BEGIN:VBODY")+11; // 11 is the length of "BEGIN:VBODY"
int endId = str.IndexOf("END:VBODY");
string result = str.Substring(startId, endId-startId);
Console.WriteLine(result);
Output:
Date:8/11/2013 11:59:00 PM
thi is a test message
Hello this is a test message on line 2
ideone demo

Here is a solution using Regular Expressions,
string text = #"N:
TEL:+65123345
END:VCARD
BEGIN:VENV
BEGIN:VBODY
Date:8/11/2013 11:59:00 PM
thi is a test message
Hello this is a test message on line 2
END:VBODY
END:VENV
END:VENV
END:VMSG";
string pattern = #"BEGIN:VBODY(?<Value>[a-zA-Z0-9\r\n.\S\s ]*)END:VBODY";//Pattern to match text.
Regex rgx = new Regex(pattern, RegexOptions.Multiline);//Initialize a new Regex class with the above pattern.
Match match = rgx.Match(text);//Capture any matches.
if (match.Success)//If a match is found.
{
string value2 = match.Groups["Value"].Value;//Capture match value.
MessageBox.Show(value2);
}
Demo here.
and now a non-regex solution,
string text = #"N:
TEL:+65123345
END:VCARD
BEGIN:VENV
BEGIN:VBODY
Date:8/11/2013 11:59:00 PM
thi is a test message
Hello this is a test message on line 2
END:VBODY
END:VENV
END:VENV
END:VMSG";
int startindex = text.IndexOf("BEGIN:VBODY") + ("BEGIN:VBODY").Length;//The just start index of Date...
int length = text.IndexOf("END:VBODY") - startindex;//Length of text till END...
if (startindex >= 0 && length >= 1)
{
string value = text.Substring(startindex, length);//This is the text you need.
MessageBox.Show(value);
}
else
{
MessageBox.Show("No match found.");
}
Demo here.
Hope it helps.

Related

Scala regex on a whole column

I have the following pattern that I could parse using pandas in Python, but struggle with translating the code into Scala.
grade string_column
85 (str:ann smith,14)(str:frank chase,15)
86 (str:john foo,15)(str:al more,14)
In python I used:
df.set_index('grade')['string_column']\
.str.extractall(r'\((str:[^,]+),(\d+)\)')\
.droplevel(1)
with the output:
grade 0 1
85 str:ann smith 14
85 str:frank chase 15
86 str:john foo 15
86 str:al more 14
In Scala I tried to duplicate the approach, but it's failing:
import scala.util.matching.Regex
val pattern = new Regex("((str:[^,]+),(\d+)\)")
val str = "(str:ann smith,14)(str:frank chase,15)"
println(pattern findAllIn(str)).mkString(","))
There are a few notes about the code:
There is an unmatched parenthesis for a group, but that one should be escaped
The backslashes should be double escaped
In the println you don't have to use all the parenthesis and the dot
findAllIn returns a MatchIterator, and looping those will expose a matched string. Joining those matched strings with a comma, will in this case give back the same string again.
For example
import scala.util.matching.Regex
val pattern = new Regex("\\((str:[^,]+),(\\d+)\\)")
val str = "(str:ann smith,14)(str:frank chase,15)"
println(pattern findAllIn str mkString ",")
Output
(str:ann smith,14),(str:frank chase,15)
But if you want to print out the group 1 and group 2 values, you can use findAllMatchIn that returns a collection of Regex Matches:
import scala.util.matching.Regex
val pattern = new Regex("\\((str:[^,]+),(\\d+)\\)")
val str = "(str:ann smith,14)(str:frank chase,15)"
pattern findAllMatchIn str foreach(m => {
println(m.group(1))
println(m.group(2))
}
)
Output
str:ann smith
14
str:frank chase
15
In Python, Series.str.extractall only returns captured substrings. In Scala, findAllIn returns the matched values if you do not query its matchData property that in its turn contains a subgroups property.
So, to get the captures only in Scala, you need to use
val pattern = """\((str:[^,()]+),(\d+)\)""".r
val str = "(str:ann smith,14)(str:frank chase,15)"
(pattern findAllIn str).matchData foreach {
m => println(m.subgroups.mkString(","))
}
Output:
str:ann smith,14
str:frank chase,15
See the Scala online demo.
Here, m.subgroups accesses all subgroups (captures) of each match (m).
Also, note you do not need to double backslashes in triple-quoted string literals. \((str:[^,()]+),(\d+)\) matches
\( - a ( char
(str:[^,()]+) - Group 1: str: and one or more chars other than ,, ( and )
, - a comma
(\d+) - Group 2: one or more digits
\) - a ) char.
If you just want to get all matches without captures, you can use
val pattern = """\((str:[^,]+),(\d+)\)""".r
println((pattern findAllIn str).matchData.mkString(","))
Output:
(str:ann smith,14),(str:frank chase,15)
See the online demo.

Dart Regex: Only allow dot and numbers

I need to format the price string in dart.
String can be: ₹ 2,19,990.00
String can be: $1,114.99
String can be: $14.99
What I tried:
void main() {
String str = "₹ 2,19,990.00";
RegExp regexp = RegExp("(\\d+[,.]?[\\d]*)");
RegExpMatch? match = regexp.firstMatch(str);
str = match!.group(1)!;
print(str);
}
What my output is: 2,19
What my output is: 1,114
What my output is: 14.99
Expected output: 219990.00
Expected output: 1114.99
Expected output: 14.99 (This one is correct because there is no comma)
The simplest solution would be to replace all non-digit/non-dot characters with nothing.
The most efficient way to do that is:
final re = RegExp(r"[^\d.]+");
String sanitizeCurrency(String input) => input.replaceAll(re, "");
You can't do it by matching because a match is always contiguous in the source string, and you want to omit the embedded ,s.
You can use this regex for search:
^\D+|(?<=\d),(?=\d)
And replace with an empty string i.e. "".
RegEx Details:
^: Start
\D+: Match 1+ non-digit characters
|: OR
(?<=\d),(?=\d): Match a comma if it surrounded with digits on both sides
RegEx Demo
Code: Using replaceAll method:
str = str.replaceAll(RegExp(r'^\D+|(?<=\d),(?=\d)'), '');

How to return/print matches on a string in RegEx in Flutter/Dart? [duplicate]

This question already has an answer here:
How to put all regex matches into a string list
(1 answer)
Closed 1 year ago.
I want to return a pattern through regEx in flutter every time it' found, I tested using the Regex operation it worked on the same string, returning the match after that included match 'text:' to '}' letters, but it does not print the matches in the flutter application.
The code I am using:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
print("allMatches : "+exp.allMatches(myString).toString());
The output print statement is printing I/flutter ( 5287): allMatches : (Instance of '_RegExpMatch', Instance of '_RegExpMatch')
instead of text: PM
Following is the screenshot of how it is parsing on regexr.com
Instead of using a non greedy match with a lookahead, I would suggest using a negated character class matching any char except } in capture group 1, and match the } after the group to prevent some backtracking.
\b(text:[^}]+)}
You can loop the result from allMatches and print group 1:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"\b(text:[^}]+)}");
for (var m in exp.allMatches(myString)) {
print(m[1]);
}
Output
text: PM
You need to use map method to retrieve the string from the matches:
String myString = '{boundingBox: 150,39,48,25, text: PM},';
RegExp exp = RegExp(r"text:(.+?(?=}))");
final matches = exp.allMatches(myString).map((m) => m.group(0)).toString();
print("allMatches : $matches");

Regular expression to match from the end of a match condition

I want to match from the end of a result from a or condition in regular expression.
$a = 'SI-#CL#¤1801 BARBER LANE#CL#MILPITAS CA 95035#CL#FONE 1-408-943-0600#CL#FAX 1-408-943-0484#CL#¤CANCEL BY 5 PM - RQST-NO FEATHER';
$pat = '/^(?(?=SI)(?<matchfromend>[A-Z]+$)|(?<else>.*))/';
i want to match CANCEL BY 5 PM - RQST-NO FEATHER only if string starts from SI-
Any suggestion ??
Thanks
Your (?(?=SI)(?<matchfromend>[A-Z]+$) regex part does not consume arbitrary characters from the beginning of the string up to the end (?<matchfromend>[A-Z]+$ pattern.
You can use the following regex:
'~^(?(?=SI).*#¤(?<matchfromend>.+$)$|(?<else>.*))~'
See the regex demo
Explanation:
^ - start of string
(?(?=SI).*#¤(?<matchfromend>.+$)$|(?<else>.*)) - a conditional:
If SI appears at the start ((?=SI)) match 0+ characters other than a newline up to the last #¤, and capture 1+ characters other than a newline up to the end of the string into Group "matchfromend"
If there is no SI at the start, match 0+ characters other than a newline up to the end of the line.
Another NON-REGEX approach
Check if a string starts with SI and if yes, explode with #¤ and get the last item. If not, use the whole string.
See IDEONE demo:
$str = "SI-#CL#¤1801 BARBER LANE#CL#MILPITAS CA 95035#CL#FONE 1-408-943-0600#CL#FAX 1-408-943-0484#CL#¤CANCEL BY 5 PM - RQST-NO FEATHER"; // => CANCEL BY 5 PM - RQST-NO FEATHER
//$str = "#CL#¤1801 BARBER LANE#CL#MILPITAS CA 95035#CL#FONE 1-408-943-0600#CL#FAX 1-408-943-0484#CL#¤CANCEL BY 5 PM - RQST-NO FEATHER";
$res = $str;
if (strrpos($str, "SI", -strlen($str)) !== false) { // starts with SI
$arr = explode("#¤", $str);
if (!empty($arr)){
$res = array_pop($arr);
}
}
echo $res;

regex not matching correctly

First of all, I would like an opinion if using regex is even the best solution here, I'm fairly new to this area and regex is the first thing I found and it seemed somewhat easy to use, until I need to grab a long section of text out of a line lol. I'm using a vb.net environment for regex.
Basically, I'm taking this line here:
21:24:55 "READ/WRITE: ['PASS',false,'27880739',[40,[459.313,2434.11,0.00221252]],[["ItemFlashlight","ItemWatch","ItemMap","ItemKnife","ItemEtool","ItemGPS","ItemHatchet","ItemCompass","ItemMatchbox","M9SD","ItemFlashlightRed","NVGoggles","Binocular_Vector","ItemToolbox","M4A1_AIM_SD_camo"],["ItemPainkiller","ItemMorphine","ItemSodaPepsi","FoodSteakCooked",["30Rnd_556x45_StanagSD",29],"30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD",["15Rnd_9x19_M9SD",12],["15Rnd_9x19_M9SD",10],"15Rnd_9x19_M9SD","15Rnd_9x19_M9SD","ItemBandage"]],["DZ_Backpack_EP1",[["BAF_AS50_TWS"],[1]],[["FoodSteakCooked","ItemPainkiller","ItemMorphine","ItemSodaCoke","5Rnd_127x99_as50","ItemBloodbag"],[2,1,1,2,4,1]]],[316,517,517],Sniper1_DZ,0.94]"
Using the following regex:
\[\[([\w|_|\""|,]*)\],\[([\w|_|\""|,|\[|\]]*)\]\],
To try and get the following:
[["ItemFlashlight","ItemWatch","ItemMap","ItemKnife","ItemEtool","ItemGPS","ItemHatchet","ItemCompass","ItemMatchbox","M9SD","ItemFlashlightRed","NVGoggles","Binocular_Vector","ItemToolbox","M4A1_AIM_SD_camo"],["ItemPainkiller","ItemMorphine","ItemSodaPepsi","FoodSteakCooked",["30Rnd_556x45_StanagSD",29],"30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD","30Rnd_556x45_StanagSD",["15Rnd_9x19_M9SD",12],["15Rnd_9x19_M9SD",10],"15Rnd_9x19_M9SD","15Rnd_9x19_M9SD","ItemBandage"]]
However either my regex is flawed, or my vb.net code is. It only displays the following data:
[["ItemFlashlight","ItemWatch","ItemMap","ItemKnife","ItemEtool","ItemGPS","ItemHatchet","ItemCompass","ItemMatchbox","M9SD","ItemFlashlightRed","NVGoggles","Binocular_Vector","ItemToolbox","M4A1_AIM_SD_camo"],["ItemPainkiller","ItemMorphine","ItemSodaPepsi",
My vb.net code in case you need to peek at it is:
ListView1.Clear()
Call initList(Me.ListView1)
My.Computer.FileSystem.CurrentDirectory = My.Settings.cfgPath
My.Computer.FileSystem.CopyFile("arma2oaserver.RPT", "tempRPT.txt")
Dim ScriptLine As String = ""
Dim path As String = My.Computer.FileSystem.CurrentDirectory & "\tempRPT.txt"
Dim lines As String() = IO.File.ReadAllLines(path, System.Text.Encoding.Default)
Dim que = New Queue(Of String)(lines)
ProgressBar1.Maximum = lines.Count + 1
ProgressBar1.Value = 0
Do While que.Count > 0
ScriptLine = que.Dequeue()
ScriptLine = LCase(ScriptLine)
If InStr(ScriptLine, "login attempt:") Then
Dim rtime As Match = Regex.Match(ScriptLine, ("(\d{1,2}:\d{2}:\d{2})"))
Dim nam As Match = Regex.Match(ScriptLine, "\""([^)]*)\""")
Dim name As String = nam.ToString.Replace("""", "")
Dim next_line As String = que.Peek 'Read next line temporarily 'This is where it would move to next line temporarily to read from it
next_line = LCase(next_line)
If InStr(next_line, "read/write:") > 0 Then 'Or InStr(next_line, "update: [b") > 0 Then 'And InStr(next_line, "setmarkerposlocal.sqf") < 1 Then
Dim coords As Match = Regex.Match(next_line, "\[(\d+)\,\[(-?\d+)\.\d+\,(-?\d+)\.\d+,([\d|.|-]+)\]\]")
Dim inv As Match = Regex.Match(next_line, "\[\[([\w|_|\""|,]*)\],\[([\w|_|\""|,|\[|\]]*)\]\],") '\[\[([\w|_|\""|,]*)\],\[([\w|_|\""|,|\[|\]]*)\]\],
'\[\[([\w|_|\""|,]*)\],\[([\w|_|\""|,|\[|\]]*)\]\]:\[([\w|_|\""|,|\[|\]]*)\]\:
Dim back As Match = Regex.Match(next_line, "\""([\w|_]+)\"",\[\[([\w|_|\""|,]*)\],\[([\d|,]*)\]\],\[\[([\w|_|\""|,]*)\],\[([\d|,]*)\]\]")
Dim held As Match = Regex.Match(next_line, "\[\""([\w|_|\""|,]+)\""\,\d+\]")
With Me.ListView1
.Items.Add(name.ToString)
With .Items(.Items.Count - 1).SubItems
.Add(rtime.ToString)
.Add(coords.ToString)
.Add(inv.ToString)
.Add(back.ToString)
.Add(held.ToString)
End With
End With
End If
End If
ProgressBar1.Value += 1
Loop
My.Computer.FileSystem.DeleteFile("tempRPT.txt")
ProgressBar1.Value = 0
The odd thing is, when I test my regex in Expresso it gets the full, correct match. So I don't know what I'm doing wrong.
I'm not sure what's wrong with the regex you have, but the first match off of this one seems to work fine:
\[\[.*?\]\]
Hope this helps.
-EDIT-
The problem isn't the regex, it's that ListView is truncating the display of the string. See here
Try this regular expression instead: \Q[[\E(?:(?!\Q[[\E).)+]]
http://regex101.com/r/zP1aC5
If you need a backref, use \Q[[\E((?:(?!\Q[[\E).)+)]]
Perhaps you should specify whether you are working with single line or multi line input text. Depending on your input text format, try with:
Dim variableName as Match = Regex.Match("input", "pattern", RegexOptions.SingleLine);
or
Dim variableName as Match = Regex.Match("input", "pattern", RegexOptions.Multiline);