开发者

How do I search for a string that is not inside quotation marks?

i would like to search for a string lets say for "//bazinga" but only if it is not inside quotation marks (single or double). when i say quotation marks i mean not escaped ones.

for example.

using this as input should return 13 (index of the match found)

"the fox is" //bazinga

and using this as input should return 18 (since the quotation marks around the string are escaped)

"bla bla \"//bazinga\"

using this as input should return -1 (not found)

"bla bla \"//bazinga"

using this as input should return 16 (the first one is ins开发者_运维知识库ide quotes so dont count)

"bla //bzinga"  //bazinga

using either of these as input should return -1 (not found)

"bbbb //bazinga"
'bbbb //bazinga'


I would suggest to have a look to :

RegEx library for strings

It contains a lot of RegEx that you can test directly on the site and change according to your needs. I always use it as source whenever I need to work with RegEx. You can use the single and double quotes as "escape chars" and define your RegEx accordingly.


You need a bit of parsing to do that. You can search for either escaped quotation marks, a quoted string, or the text that you want to match, and analyse what you get. Something like:

MatchCollection matches = Regex.Matches(
  input,
  "(/\"|/'|\"[^\"]*\"|'[^']*'|" + Regex.Escape("//bazinga") + ")"
);

By searching for escaped quotation marks, then quoted strings, then the text, you make sure that a quoted string is not escaped, and that the text is not inside a quoted string.

If any of the mathces is your text, you found it.

Edit

With this input:

string input = "asdf /\" /' '//bazinga'  \"//bazinga\" //bazinga";

I ran the match, and then showed the result using:

foreach (Match match in matches) {
  Console.WriteLine("{0} {1}", match.Index, match.Value);
}

Output:

5 /"
8 /'
11 '//bazinga'
24 "//bazinga"
36 //bazinga

You can use code like this to get the indexes of the actual hits in the matches collection:

int[] found =
  matches.Cast<Match>()
  .Where(m => m.Value == "//bazinga")
  .Select(m => m.Index)
  .ToArray();


With this input:

This is "bazinga" asdf

And this regular expression:

["][a-zA-Z\x20]+["]

You can run Split instead of Search and get this output:

This is
asdf

I recommend getting this free tool: Expresso

http://www.ultrapico.com/


int getIndexWithoutQ(string find)
{
int index = -1;
string search = "";
for (int i = 0; i < find.Length; i++)
{
while (find[i] == '\"')
 i++;
if (i < find.Length)
  search += find[i];
}

if (search.IndexOf(find) == -1)
   return -1;
while (this.insideQ(all, find, index = all.IndexOf(find)));
return index;
}

bool insideQ(string all, string find, int begin)
{

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜