I am very new with regex. I want to search for multiple words in a string by ignoring common words like "in", "of", "the" and special characters like comma, backslash etc.
My Code
Dim StringToSearchFrom As String = "Thus, one shifts one's focus in a variety of directions all at the same time"
Dim PhraseToSearch As String = "focus variety directions"
Dim found1 As Match = Regex.Match(StringToSearchFrom, Regex needed)
If found1.Success Then
MsgBox(found1.Index)
Else
First regex should ignore the complete words "in", "a" and "of" while trying to find and then return the index of the first word (focus ) of PhraseToSearch. Thanks
You can use the following regular expression, that you will have to build dynamically. Here is a proof-of-concept example that will capture "focus variety" in your string ignoring "a" and "in":
Public Dim MyRegex As Regex = New Regex( _
"focus(?:(?:\b(?:in|of|a|the)\b\s*|[\p{P}\p{S}\p{Z}]*)*)variety", _
RegexOptions.IgnoreCase _
Or RegexOptions.CultureInvariant _
Or RegexOptions.Compiled _
)
Explanation:
To make a part of string optional, we should still be able to capture it in the pattern. If you replace all optional substrings in your query string with (?:(?:\b(?:in|of|a|the)\b\s*|[\p{P}\p{S}\p{Z}]*)*), you will be able to match any words in the word list (?:in|of|a|the) (update with your word list), punctuation \p{P}, symbols \p{S}, whitespace \p{Z}.
Dim StringToSearchFrom As String = "Thus, one shifts one's focus in a variety of directions all at the same time"
Dim PhraseToSearch As String = "focus variety directions"
Dim optional_pattern As String = "(?:(?:\b(?:in|of|a|the)\b\s*|[\p{P}\p{S}\p{Z}]*)*)"
Dim rgx_Optional As New Regex(optional_pattern)
PhraseToSearch = rgx_Optional.Replace(PhraseToSearch, optional_pattern)
Dim rgx_Search As New Regex(PhraseToSearch)
' And then apply our regex
Dim found1 As Match = rgx_Search.Match(StringToSearchFrom)
If found1.Success Then
MsgBox(found1.Index)
Else
Related
I have several strings, e.g.
(3)_(9)--(11).(FT-2)
(10)--(20).(10)/test--(99)
I am trying Regex.Match(here I do no know) to get a list like this:
First sample:
3
_
9
--
11
.
FT-1
Second Sample:
10
--
20
.
10
/test--
99
So there are several numbers in brackets and any text between them.
Can anyone help me doing this in vb.net? A given string returns this list?
One option is to use the Split method of [String]
"(3)_(9)--(11).(FT-2)".Split('()')
Another option is to match everything excluding ( and )
As regex, this would do [^()]+
Breakdown
"[^()]" ' Match any single character NOT present in the list “()”
"+" ' Between one and unlimited times, as many times as possible, giving back as needed (greedy)
You can use following block of code to extract all matches
Try
Dim RegexObj As New Regex("[^()]+", RegexOptions.IgnoreCase)
Dim MatchResults As Match = RegexObj.Match(SubjectString)
While MatchResults.Success
' matched text: MatchResults.Value
' match start: MatchResults.Index
' match length: MatchResults.Length
MatchResults = MatchResults.NextMatch()
End While
Catch ex As ArgumentException
'Syntax error in the regular expression
End Try
This should work:
Dim input As String = "(3)_(9)--(11).(FT-2)"
Dim searchPattern As String = "\((?<keep>[^)]+)\)|(?<=\))(?<keep>[^()]+)"
Dim replacementPattern As String = "${keep}" + Environment.NewLine
Dim output As String = RegEx.Replace(input, searchPattern, replacementPattern)
The simplest way is to use Regex.Split (formulated as a little console test):
Dim input = {"(3)_(9)--(11).(FT-2)", "(10)--(20).(10)/test--(99)"}
For Each s As String In input
Dim parts = Regex.Split(s, "\(|\)")
Console.WriteLine($"Input = {s}")
For Each p As String In parts
Console.WriteLine(p)
Next
Next
Console.ReadKey()
So basically we have a one-liner for the regex part.
The regular expression \(|\) means: split at ( or ) where the braces are escaped with \ because of their special meaning within regex.
The slightly shorter regex [()] where the desired characters are enclosed in [] would produce the same result.
I have some string, like this one:[H]GOODYEAR[/H] [H]TIRE[/H] & RUBBER COMPANY
I need to get words that inside [H] [/H] node inside this string.
I created this Regex Pattern: \[H](.*?)\[\/H]
I've tried to use Regex.Split Method to get this words. Here's my code:
Dim pattern As String = "\[H](.*?)\[\/H]"
Dim input As String = "[H]GOODYEAR[/H] [H]TIRE[/H] & RUBBER COMPANY"
Dim SearchedResult() As String = Regex.Split(input, pattern, RegexOptions.IgnoreCase)
But then I realized, that this Split gives me everything, which is not words I need.
My question: How to get correct words? Is that any way to REVERSE Regex pattern? Or any better way to get my result?
Instead of splitting the string, you should use Regex.Matches method.
Note: I used inline modifiers (?si), the s (dotAll) modifier which forces the dot . to match newline characters in case the nodes span across multiple lines, and the i modifier for case-insensitive matching.
Dim input As String = "[H]GOODYEAR[/H] [H]TIRE[/H] & RUBBER COMPANY"
For Each m As Match In Regex.Matches(input, "(?si)\[H](.*?)\[/H]")
Console.WriteLine(m.Groups(1).Value)
Next
Output
GOODYEAR
TIRE
I have a Full Name as input and want to split the whole full name word by word but it should:
Do not Split the word if contains a Hyphen e.g. REES-MOGG
Should Split the word if contains an Underscore e.g REES_MOGG
HYPHEN
Example:
MRS C REES-MOGG
Result:
MRS
C
REES-MOGG
UNDERSCORE
Example:
MRS C REES_MOGG
Result :
MRS
C
REES
MOGG
I am currently using the code below but in vain:
Dim str As String() = Regex.Split(names, "\s+")
Just split on "\s+|_", that will split on whitespace, and also on underscores. Your code would be:
Dim str As String() = **Regex.Split(names, "\s+|_")**
Demo.
For it to split on ampersands too, just add |\& to the string:
Dim str As String() = **Regex.Split(names, "\s+|_|\&")**
Demo.
use this :
Dim str As String() = Regex.Split(names, "[\s_]+")
Dim str As String() = names.Split({" ", "_", "&", vbTab}, StringSplitOptions.RemoveEmptyEntries)
In order to make your script split on white-space and underscores you simply need to add a character group [ ] around the white-space character \s in your regex and then add any other symbols which you want to spit on into that group.
Dim str As String() = Regex.Split(names, "[\s_]+")
I don't know much about VB .NET, but you should change your RegEx for sure.
here is an example, though I tested on Javascript.
Dim matchForHyphen As MatchCollection = Regex.Matches("MRS C REES-MOGG","[\w]*[^_]*")
Dim matchForUnderscore As MatchCollection = Regex.Match("MRS C REES_MOGG","[\w]*[^_]*")
Then you should cycle through the Match objects to get the results.
eg. matchForHyphen[i] in a For cycle. or a For Each statement
Hope it helps
I have a list of original words and replace with words which I want to replace occurrence of the original words in some sentences to the replace words.
For example my list:
theabove the above
myaddress my address
So the sentence "This is theabove." will become "This is the above."
I am using Regular Expression in VB like this:
Dim strPattern As String
Dim regex As New RegExp
regex.Global = True
If Not IsEmpty(myReplacementList) Then
For intRow = 0 To UBound(myReplacementList, 2)
strReplaceWith = IIf(IsNull(myReplacementList(COL_REPLACEMENTWORD, intRow)), " ", varReplacements(COL_REPLACEMENTWORD, intRow))
strPattern = "\b" & myReplacementList(COL_ORIGINALWORD, intRow) & "\b"
regex.Pattern = strPattern
TextToCleanUp = regex.Replace(TextToReplace, strReplaceWith)
Next
End If
I loop all entries in my list myReplacementList against the text TextToReplace I want to process, and the replacement have to be whole word so I used the "\b" token around the original word.
It works well but I have a problem when the original words contain some special characters for example
overla) overlay
I try to escape the ) in the pattern but it does not work:
\boverla\)\\b
I can't replace the sentence "This word is overla) with that word." to "This word is overlay with that word."
Not sure what is missing? Is regular expression the way to the above scenario?
I'd use string.replace().
That way you don't have to escape special chars .. only these: ""!
See here for examples: http://www.dotnetperls.com/replace-vbnet
Regex is good if your looking for patterns. Or renaming your mp3 collection ;-) and much, much more. But in your case, I'd use string.replace().
I am trying to split a long string based on an array of words. For Example:
Words: trying, long, array
Sentence: "I am trying to split a long string based on an array of words."
Resulting string array:
I am
trying
to split a
long
string based on an
array
of words
Multiple instances of the same word is likely, so having two instances of trying cause a split, or of array, will probably happen.
Is there an easy way to do this in .NET?
The easiest way to keep the delimiters in the result is to use the Regex.Split method and construct a pattern using alternation in a group. The group is key to including the delimiters as part of the result, otherwise it will drop them. The pattern would look like (word1|word2|wordN) and the parentheses are for grouping. Also, you should always escape each word, using the Regex.Escape method, to avoid having them incorrectly interpreted as regex metacharacters.
I also recommend reading my answer (and answers of others) to a similar question for further details: How do I split a string by strings and include the delimiters using .NET?
Since I answered that question in C#, here's a VB.NET version:
Dim input As String = "I am trying to split a long string based on an array of words."
Dim words As String() = { "trying", "long", "array" }
If (words.Length > 0)
Dim pattern As String = "(" + String.Join("|", words.Select(Function(s) Regex.Escape(s)).ToArray()) + ")"
Dim result As String() = Regex.Split(input, pattern)
For Each s As String in result
Console.WriteLine(s)
Next
Else
' nothing to split '
Console.WriteLine(input)
End If
If you need to trim the spaces around each word being split you can prefix and suffix \s* to the pattern to match surrounding whitespace:
Dim pattern As String = "\s*(" + String.Join("|", words.Select(Function(s) Regex.Escape(s)).ToArray()) + ")\s*"
If you're using .NET 4.0 you can drop the ToArray() call inside the String.Join method.
EDIT: BTW, you need to decide up front how you want the split to work. Should it match individual words or words that are a substring of other words? For example, if your input had the word "belong" in it, the above solution would split on "long", resulting in {"be", "long"}. Is that desired? If not, then a minor change to the pattern will ensure the split matches complete words. This is accomplished by surrounding the pattern with a word-boundary \b metacharacter:
Dim pattern As String = "\s*\b(" + String.Join("|", words.Select(Function(s) Regex.Escape(s)).ToArray()) + ")\b\s*"
The \s* is optional per my earlier mention about trimming.
You could use a regular expression.
(.*?)((?:trying)|(?:long)|(?:array))(.*)
will give you three groups if it matches:
1) The bit before the first instance of any of the split words.
2) The split word itself.
3) The rest of the string.
You can keep matching on (3) until you run out of matches.
I've played around with this but I can't get a single regex that will split on all instances of the target words. Maybe someone with more regex-fu can explain how.
I've assumed that VB has regex support. If not, I'd recommend using a different language. Certainly C# has regexes.
You can split with " ",
and than go through the words and see which one is contained in the "splitting words" array
Dim testS As String = "I am trying to split a long string based on an array of words."
Dim splitON() As String = New String() {"trying", "long", "array"}
Dim newA() As String = testS.Split(splitON, StringSplitOptions.RemoveEmptyEntries)
Something like this
Dim testS As String = "I am trying to split a long string based on a long array of words."
Dim splitON() As String = New String() {"long", "trying", "array"}
Dim result As New List(Of String)
result.Add(testS)
For Each spltr As String In splitON
Dim NewResult As New List(Of String)
For Each s As String In result
Dim a() As String = Strings.Split(s, spltr)
If a.Length <> 0 Then
For z As Integer = 0 To a.Length - 1
If a(z).Trim <> "" Then NewResult.Add(a(z).Trim)
NewResult.Add(spltr)
Next
NewResult.RemoveAt(NewResult.Count - 1)
End If
Next
result = New List(Of String)
result.AddRange(NewResult)
Next
Peter, I hope the below would be suitable for Split string by array of words using Regex
// Input
String input = "insert into tbl1 inserttbl2 insert into tbl2 update into tbl3
updatededle into tbl4 update into tbl5";
//Regex Exp
String[] arrResult = Regex.Split(input, #"\s+(?=(?:insert|update|delete)\s+)",
RegexOptions.IgnoreCase);
//Output
[0]: "insert into tbl1 inserttbl2"
[1]: "insert into tbl2"
[2]: "update into tbl3 updatededle into tbl4"
[3]: "update into tbl5"