Making RegEx Match Bold - VB.NET - regex

This is my current RegEx: \[b\](.*?)\[/b\]
That works perfectly fine, it replaces exactly what I want it to. But, I'm trying to figure out how to make it replace the string between [b][/b] with a bold string, but the actual text stays the same.
Example string: [b]This is an example![/b]
Desired output: This is an example!
I'm using VB.NET and this is what I currently have:
Dim reg As New Regex("\[b\](.*?)\[/b\]")
Dim str As String = String.Empty
For Each m As Match In reg.Matches(MainBox.Text)
str = reg.Replace(MainBox.Text, "test")
Next
Preview.Show()
Preview.RichTextBox1.Text = str
Preview.Size = New Size(Preview.MaximumSize.Width, Preview.MaximumSize.Height)

You need to set the start of the selection, and set the attributes of the text before inserting it.
Preview.RichTextBox1.SelectionStart = Preview.RichTextBox1.Text.Length
Preview.RichTextBox1.SelectionFont = New Font("Tahoma", 12, FontStyle.Bold)
Preview.RichTextBox1.SelectedText = str

Related

Trying to extract value with Regex

This is the text:
"{\"step_naAme\": \"\", \"nonce_code\": \"HGtDXNmPhb\", \"user_id\": 1545816852, \"is_stateless\": false}"
I just want to extract HGtDXNmPhb and 1545816852 without the rest. I tried:
dim text as string = regex.match(text=fromstring,"""{\""step_name\"":\""\"", \""nonce_code\"": \""(.*?)\"", \""user_id\"": (.*?),\""is_stateless\"": false}""").groups(1).value
the response was empty every time. please help, thanks.
Here's one way, if you know for fact that the values will always be in the same place in the array (make sure you escape the original string properly first of course):
Dim strString As String = """{\""step_naAme\"": \""\"", \""nonce_code\"": \""HGtDXNmPhb\"", \""user_id\"": 1545816852, \""is_stateless\"": false}"""
Dim strSearch() As String = Regex.Split(strString, "\W+")
Debug.Writeline(strSearch(3) & " " & strSearch(5))
Result:
HGtDXNmPhb 1545816852

Removing data from string using regular expressions in C Sharp

Definitely I'm not good using regular expressions but are really cool!, Now I want to be able to get only the name "table" in this string:
[schema].[table]
I want to remove the schema name, the square brackets and the dot.
so I will get only the work table
I tried this:
string output = Regex.Replace(reader["Name"].ToString(), #"[\[\.\]]", "");
So you came up with a new idea?? Here is what you can try:
string input = "[schema].[table]";
// replacing the first thing into [] with the dot with empty
string one = Regex.Replace(input, #"^\[.*?\]\.", "");
// or replacing anything before the dot with empty
// string two = Regex.Replace(input, #".*[.]", "");
try this
string strRegex = #"^\[.*?\]\.";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"[schema].[table]";
string strReplace = #"";
var result=myRegex.Replace(strTargetString, strReplace);
Console.WriteLine(result);
Why do you want to do replace if you just want to extract part of string?
string table = Regex.Match("[schema].[table]", #"\w+(?=]$)").Value;
It works even in case if you don't have schema.

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);

Get/split text inside brackets/parentheses

Just have a list of words, such as:
gram (g)
kilogram (kg)
pound (lb)
just wondering how I would get the words within the brackets for example get the "g" in "gram (g)" and dim it as a new string.
Possibly using regex?
Thanks.
Use split function ..
strArr = str.Split("(") ' splitting 'gram (g)' returns an array ["gram " , "g)"] index 0 and 1
strArr2 = strArr[1].Split(")") ' splitting 'g)' returns an array ["g " ..]
the string is in
strArr2[0]
Edit
you want getAbbrev and getAbbrev2 to be arrays
try
Dim getAbbrev As String() = Str.Split("(")
Dim getAbbrev2 as String() = getAbbrev[1].Split(")")
To do it without declaring arrays you can do
"gram (g)".Split("(")[1].Split(")")[0]
but that's unreadable
Edit
You have some very trivial errors. I would suggest you strengthen your understanding on objects and declarations first. Then you can look into invoking methods. I rather have you understand it than give it to you. Re-read the book you have or look for a basic tutorial.
Dim unit As String = 'make sure this is the actual string you are getting, not sure where you are supposed to get the string value from => ie grams (g)
Dim getAbbrev As String() = unit.Split("(") 'use unit not Str - Str does not exist
Dim getAbbrev2 As String() = getAbbrev[1].Split(")") 'As no as - case sensitive
for the last line reference getAbbrev2 instead of the unknown abbrev2
Fun with Regular Expressions (I'm really not an expert here, but tested and works)
Imports System.Text.RegularExpressions
.....
Dim charsToTrim() As Char = { "("c, ")"c }
Dim test as String = "gram (g)" + Environment.NewLine +
"kilogram (kg)" + Environment.NewLine +
"pound (lb)"
Dim pattern as String = "\([a-zA-Z0-9]*\)"
Dim r As Regex = new Regex(pattern, RegexOptions.IgnoreCase)
Dim m As Match = r.Match(test)
While(m.Success)
System.Diagnostics.Debug.WriteLine("Match" + "=" + m.Value.ToString())
Dim tempText as String = m.Value.ToString().Trim(charsToTrim)
System.Diagnostics.Debug.WriteLine("String Trimmed" + "=" + tempText)
m = m.NextMatch()
End While
You can split at the space and remove the parens from the second token (by replacing them with an empty string).
A regex is also an option, and is very simple, its pattern is
\w+\s+\((\w+)\)
Which means, a word, then at least one space, then opening parens, then in real regex parens you search for a word, and, eventually a closing paren. The inner parentheses are capturing parentheses, which make it possible to refer to the unit g, kg, lb.

Is it possible to use your match from the match box in the replace box with Regex/Replace?

I have a long list like this
sb.AppendLine(product.product_id.Length.ToString())
I want to use regex search and replace to change every line to something like this
sb.AppendLine("product.product_id " + product.product_id.Length.ToString())
Is this possible to do with regex search and replace?
What do I put in the search box and what to I put in the replace box?
Is it possible to use your match from the match box in the replace box?
Yes it is possible, using capturing parentheses.
I assume that product_id is variable.
Search:
sb\.AppendLine\(product\.(.+)\.Length\.ToString\(\)\)
Replace:
sb.AppendLine("product.$1 " + product.$1.Length.ToString())
in vb .net
Dim str As String
str = "sb.AppendLine(product.product_id.Length.ToString())"
Dim RegexObj As Regex
RegexObj = New Regex("^sb.AppendLine((.*).Length.ToString())$")
Dim res As String
res = RegexObj.Replace(str, "sb.AppendLine(""$1"" + product.product_id.Length.ToString())")
in c# .net
string str = null;
str = "sb.AppendLine(product.product_id.Length.ToString())";
Regex RegexObj = default(Regex);
RegexObj = new Regex("^sb\.AppendLine\((.*)\.Length\.ToString\(\)\)$");
string res = null;
res = RegexObj.Replace(str, "sb.AppendLine(\"$1\" + product.product_id.Length.ToString())");