Removing data from string using regular expressions in C Sharp - regex

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.

Related

flutter check if string starts with RegExp

in flutter if we want to check if a string starts with a specific character...we can achieve that by:
var string = 'Dart';
string.startsWith('D'); // true
what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:
RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);
is the above code is right?!!
my goal is to check if the string starts with a letter i specify...then a RegExp....
not to check if the string starts with 'D' only and thats it...
what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:
RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);
That won't work. 'D' is a String object, and myRegExp presumably is intended to be a RegExp object. (Your syntax isn't correct; you probably want RegExp myRegExp = RegExp('[a-zA-Z0-9]');.) Both String and RegExp derive from a Pattern base class, but Pattern does not provide operator+, and String.operator+ works only with other Strings. Conceptually it's unclear what adding a String and RegExp should do; return a String? Return a RegExp?
You instead should just write a regular expression that accounts for your first character:
RegExp myRegExp = RegExp('D[a-zA-Z0-9]');
However, if you want the first character to be variable, then you can't bake it into the string literal used for the RegExp's pattern.
You instead could match the two parts separately:
var prefix = 'D';
var restRegExp = RegExp(r'[a-zA-Z0-9]');
var string = 'Dart';
var startsWith =
string.startsWith(prefix) &&
string.substring(prefix.length).startsWith(restRegExp);
Alternatively you could build the regular expression dynamically:
var prefix = 'D';
var restPattern = r'[a-zA-Z0-9]';
// Escape the prefix in case it contains any special regular expression
// characters. This is particularly important if the prefix comes from user
// input.
var myRegExp = RegExp(RegExp.escape(prefix) + restPattern);
var string = 'Dart';
var startsWith = string.startsWith(myRegExp);
I think you'll want something like string.startsWith(RegExp('D' + '[a-zA-Z0-9]'));

Regular expression for splitting a string and add it to an Array

I have a string which is in the following format:
[0:2]={1.1,1,5.1.2}
My requirement here is to split the values inside curly braces after = operator, and store them in to a string array. I had tried to split part by using Substring() and IndexOf() methods, and it worked. But I needed a cleaner and elegant way to achieve this via regular expressions.
Does anybody having clues to achieve my requirement?
Here is your fully RegEx solution:
Dim input As String = "[0:2]={1.1,1,5.1.2}"
Dim match = Regex.Match(input, "\[\d:\d\]={(?:([^,]+),)*([^,]+)}")
Dim results = match.Groups(1).Captures.Cast(Of Capture).Select(Function(c) c.Value).Concat(match.Groups(2).Captures.Cast(Of Capture).Select(Function(c) c.Value)).ToArray()
Don't think it is more readable then standard split:
Dim startIndex = input.IndexOf("{"c) + 1
Dim length = input.Length - startIndex - 1
Dim results = input.Substring(startIndex, length).Split(",")
You could use a regular expression to extract the values inside the curly braces, and then use an ordinary Split:
Regex.Match("[0:2]={1.1,1,5.1.2}", "{(.*)}").Groups(1).Value.Split(","c)
Dim s As String = "[0:2]={1.1,1,5.1.2}";
Dim separatorChar as char = "="c;
Dim commaChar as char = ","c;
Dim openBraceChar as char = "{"c;
Dim closeBraceChar as char = "}"c;
Dim result() as String =
s.Split(separatorChar)(1)
.trim(openBraceChar)
.trim(closeBraceChar)
.split(commaChar);
(assuming it works! Typed on an iPad so can't verify syntax easily, but principal should be sound).
EDIT: updated to VB as downvoted for showing working .net methods in c# syntax.
if you want it using Regex
Dim s() As String=Regex.match(str,"(={)(.*)(})").Groups(1).Tostring.split(',');

Regex Error in currency

I have a big problem, I used this codes to generate the number to currency,
Dim reg = New Regex("\d+")
Dim str As String = dZ.Rows(y).Item(14).ToString().Replace(",", ""). _
Replace(".00", "").Replace("$", "").Trim
Dim match = reg.Match(str)
If match.Success Then
str = reg.Replace(str, Decimal.Parse(match.Value).ToString("C"))
End If
yes it works, but what if my amount is:
1,900.50 POC
kelvzy your solution is not very flexible. I will suggest my solution:
string cellValue = dZ.Rows[y][14];
string cleanedCellValue = Regex.Replace(s, #"\s[^\d.,]+", "");
//this will replace everything after the last digit
string decimalValue = Convert.ToDecimal(cleanedCellValue, CultureInfo.InvariantCulture);
string str = decimalValue.ToString("C");
This solution will work, when each cell uses comma as thousand separator, dot as decimal separator and any symbols as currency symbol.
In other case give me please more examples

how to remove double characters and spaces from string

Please let me how to remove double spaces and characters from below string.
String = Test----$$$$19****45#### Nothing
Clean String = Test-$19*45# Nothing
I have used regex "\s+" but it just removing the double spaces and I have tried other patterns of regex but it is too complex... please help me.
I am using vb.net
What you'll want to do is create a backreference to any character, and then remove the following characters that match that backreference. It's usually possible using the pattern (.)\1+, which should be replaced with just that backreference (once). It depends on the programming language how it's exactly done.
Dim text As String = "Test###_&aa&&&"
Dim result As String = New Regex("(.)\1+").Replace(text, "$1")
result will now contain Test#_&a&. Alternatively, you can use a lookaround to not remove that backreference in the first place:
Dim text As String = "Test###_&aa&&&"
Dim result As String = New Regex("(?<=(.))\1+").Replace(text, "")
Edit: included examples
For a faster alternative try:
Dim text As String = "Test###_&aa&&&"
Dim sb As New StringBuilder(text.Length)
Dim lastChar As Char
For Each c As Char In text
If c <> lastChar Then
sb.Append(c)
lastChar = c
End If
Next
Console.WriteLine(sb.ToString())
Here is a perl way to substitute all multiple non word chars by only one:
my $String = 'Test----$$$$19****45#### Nothing';
$String =~ s/(\W)\1+/$1/g;
print $String;
output:
Test-$19*45# Nothing
Here's how it would look in Java...
String raw = "Test----$$$$19****45#### Nothing";
String cleaned = raw.replaceAll("(.)\\1+", "$1");
System.out.println(raw);
System.out.println(cleaned);
prints
Test----$$$$19****45#### Nothing
Test-$19*45# Nothing

Making RegEx Match Bold - VB.NET

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