简体   繁体   中英

How to match number and minus operator with regex?

In fact, i'd like to match the things before and after the " ??" my code is below:

//enter code here
        Regex r = new Regex(@"(?'value'[0-9\-\./TSE]{1,}) \?\?(?'index'[A-Za-z:]{1,}");
        string s=
@"39 ??Issue:
9 ??Pages:
1307-1325 ??DOI:
10.1109/TSE.2013.14 ??Published:";

As you can see, i'd like to match these things:

value="39" index = "Issue:"
value="9" index = "Pages:"
value="1307-1325" index = "DOI:"
value="10.1109/TSE.2013.14" index = "Published:"

I think just change one or two characters in the regex can solve this problem. anyone can help?

If you simply want the information before and after the ?? , and it will always be in that format (value ?? index), then Regex is way overkill for this. Simply use String.Split :

string s= @"39 ??Issue:
9 ??Pages:
1307-1325 ??DOI:
10.1109/TSE.2013.14 ??Published:";

string[] splitValues = s.Split(new string[] { "??", "\r\n" }, StringSplitOptions.None);

for (int i = 0; i < splitValues.Length; i += 2)
{
    Console.WriteLine("value={0} index={1}", splitValues[i].Trim(), splitValues[i + 1].Trim());
}

This will split on the ?? and the newline, resulting in the output you're looking for:

value="39" index = "Issue:"
value="9" index = "Pages:"
value="1307-1325" index = "DOI:"
value="10.1109/TSE.2013.14" index = "Published:"

The coded above splits the string on ?? and \\r\\n (end of line/newline), resulting in an array of elements, with the first element being the first value, the second element being the second value, the third element being the first value of the second line, the fourth element being the second value of the second line, etc.

The for loop is pretty straight forward - the i += 2 part simply increments the loop counter by 2 (instead of the usual 1 [ i++ ]), so it prints the value and index of each line in the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM