Regex Error in currency - regex

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

Related

Replace the second char of a string

I have a string variable.
Dim str As String = "ABBCD"
I want to replace only the second 'B' character of str (I mean the second occurrence)
my code
Dim regex As New Regex("B")
Dim result As String = regex.Replace(str, "x", 2)
'result: AxxCD
'but I want: ABxCD
What's the easiest way to do this with Regular Expressions.
thanks
Dim str As String = "ABBCD"
Dim matches As MatchCollection = Regex.Matches(str, "B")
If matches.Count >= 2 Then
str = str.Remove(matches(1).Index, matches(1).Length)
str = str.Insert(matches(1).Index, "x")
End If
First we declare the string 'str', then find the matches of "B". If we found two results or more, replace the second result with "x".
How about:
resultString = Regex.Replace(subjectString, #"(B)\1", "$+x");
Use a positive lookbehind:
Dim regex As New Regex("(?<=B)B")
Live demo
If ABCABCABC should produce ABCAxCABC, then the following regex will work:
(?<=^[^B]*B[^B]*)B
Usage:
Dim result As String = Regex.Replace(str, "(?<=^[^B]*B[^B]*)B", "x")
I assume BB was just an example, it can be CC, DD, EE, etc..
Based on that, the regex below will replace any repeated character in the string.
resultString = Regex.Replace(subjectString, #"(\w)\1", "$1x");
'Alternative way to replace the second occurrence
'only of B in the string with X
Dim str As String = "ABBCD"
Dim pattern As String = "B"
Dim reg As Regex = New Regex(pattern)
Dim replacement As String = "X"
'find position of second B
Dim secondBpos As Integer = Regex.Matches(str, pattern)(1).Index
'replace that B with X
Dim result As String = reg.Replace(str, replacement, 1, secondBpos)
MessageBox.Show(result)

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.

match date pattern in the string vba excel

Edit:
Since my string became more and more complicated looks like regexp is the only way.
I do not have a lot experience in that and your help is much appreciated.
Basically from what I read on the web I construct the following exp to try matching occurrence in my sample string:
"My very long long string 12Mar2012 is right here 23Apr2015"
[0-9][0-9] + [a-zA-Z] + [0-9][0-9][0-9][0-9]
and trying this code. I do not have any match. Any good link on regexp tutorial much appreciated.
Dim re, match, RegExDate
Set re = CreateObject("vbscript.regexp")
re.Pattern = "(^[0-9][0-9] + [a-zA-Z] + [0-9][0-9][0-9][0-9]$)"
re.Global = True
For Each match In re.Execute(str)
MsgBox match.Value
RegExDate = match.Value
Exit For
Next
Thank you
This code validates the actual date from the Regexp using DateValuefor robustness
Sub Robust()
Dim Regex As Object
Dim RegexMC As Object
Dim RegexM As Object
Dim strIn As String
Dim BDate As Boolean
strIn = "My very long long string 12Mar2012 is right here 23Apr2015 and 30Feb2002"
Set Regex = CreateObject("vbscript.regexp")
With Regex
.Pattern = "(([0-9])|([0-2][0-9])|([3][0-1]))(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\d{4})"
.Global = True
If .test(strIn) Then
Set RegexMC = .Execute(strIn)
On Error Resume Next
For Each RegexM In RegexMC
BDate = False
BDate = IsDate(DateValue(RegexM.submatches(0) & " " & RegexM.submatches(4) & " " & RegexM.submatches(5)))
If BDate Then Debug.Print RegexM
Next
On Error GoTo 0
End If
End With
End Sub
thanks for all your help !!!
I managed to solve my problem using this simple code.
Dim rex As New RegExp
Dim dateCol As New Collection
rex.Pattern = "(\d|\d\d)(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\d{4})?"
rex.Global = True
For Each match In rex.Execute(sStream)
dateCol.Add match.Value
Next
Just note that on my side I'm sure that I got valid date in the string so the reg expression is easy.
thnx
Ilya
The following is a quick attempt I made. It's far from perfect.
Basically, it splits the string into words. While looping through the words it cuts off any punctuation (period and comma, you might need to add more).
When processing an item, we try to remove each month name from it. If the string gets shorter we might have a date.
It checks to see if the length of the final string is about right (5 or 6 characters, 1 or 2 + 4 for day and year)
You could instead (or also) check to see that there all numbers.
Private Const MonthList = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC"
Public Function getDates(ByVal Target As String) As String
Dim Data() As String
Dim Item As String
Dim Index As Integer
Dim List() As String
Dim Index2 As Integer
Dim Test As String
Dim Result As String
List = Split(MonthList, ",")
Data = Split(Target, " ")
Result = ""
For Index = LBound(Data) To UBound(Data)
Item = UCase(Replace(Replace(Data(Index), ".", ""), ",", ""))
For Index2 = LBound(Data) To UBound(Data)
Test = Replace(Item, List(Index2), "")
If Not Test = Item Then
If Len(Test) = 5 Or Len(Test) = 6 Then
If Result = "" Then
Result = Item
Else
Result = Result & ", " & Item
End If
End If
End If
Next Index2
Next
getDates = Result
End Function

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

Regular expression to extract numbers from long string containing lots of punctuation

I am trying to separate numbers from a string which includes %,/,etc for eg (%2459348?:, or :2434545/%). How can I separate it, in VB.net
you want only the numbers right?
then you could do it like this
Dim theString As String = "/79465*44498%464"
Dim ret = Regex.Replace(theString, "[^0-9]", String.Empty)
hth
edit:
or do you want to split by all non number chars?
then it would go like this
Dim ret = Regex.Split(theString, "[^0-9]")
You could loop through each character of the string and check the .IsNumber() on it.
This should do:
Dim test As String = "%2459348?:"
Dim match As Match = Regex.Match(test, "\d+")
If match.Success Then
Dim result As String = match.Value
' Do something with result
End If
Result = 2459348
Here's a function which will extract all of the numbers out of a string.
Public Function GetNumbers(ByVal str as String) As String
Dim builder As New StringBuilder()
For Each c in str
If Char.IsNumber(c) Then
builder.Append(c)
End If
Next
return builder.ToString()
End Function