Question get the position of one string in other string ... but a little diffrent

pooya1072

Well-known member
Joined
Jul 5, 2012
Messages
84
Programming Experience
Beginner
suppose have a string like this :
"abcdsqr efgh(sqr)efg 655*sqr+876 resqrhhg sqrfdfd sqr uytu"
i want to get the position of "sql" in this string .this string is shown in red color in the top main string. but just the position of "sql" which left side and right character for it is :
1-space
or
2-numerical operator {"(", ")", "+", "-", "*", "/", "\", "=", "^"}
or
3-or both of them

by this condition my target strings in the top main string shown with green color:
"abcdsqr efgh(sqr)efg 655*sqr+876 resqrhhg sqrfdfd sqr uytu"
how can i get the start position of this?
 
Hi,

You need to use a Loop in conjunction with IndexOf to find all the occurrences of your string "sqr". Once found, you need to use SubString to check the 4th and 5th character beyond "sqr" to see if it matches your additional requirements.

IndexOf and SubString are both methods of the String Class. Have a look here:-

String.IndexOf Method (String) (System)
String.Substring Method (Int32, Int32) (System)

Hope that helps.

Cheers,

Ian
 
I would go for regex, this is a straight forward pattern matching 'sqr' as a sub group:
        Dim q = "[ ()+*/=\\\^\-]"
        Dim pattern = q & "(sqr)" & q
        Dim input = "abcdsqr efgh(sqr)efg 655*sqr+876 resqrhhg sqrfdfd sqr uytu"
        Dim idx = From m In Regex.Matches(input, pattern).Cast(Of Match)() Select m.Groups(1).Index
        'idx contains indexes: 13 25 50

If regex is new to you I recommend this place to learn: Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns
 
I would go for regex, this is a straight forward pattern matching 'sqr' as a sub group:
        Dim q = "[ ()+*/=\\\^\-]"
        Dim pattern = q & "(sqr)" & q
        Dim input = "abcdsqr efgh(sqr)efg 655*sqr+876 resqrhhg sqrfdfd sqr uytu"
        Dim idx = From m In Regex.Matches(input, pattern).Cast(Of Match)() Select m.Groups(1).Index
        'idx contains indexes: 13 25 50

If regex is new to you I recommend this place to learn: Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns
thank you very much.this is exactly that i want.
 
Back
Top