0
String str = "USD  SBFARE 4067.71 OVDPCT 8P SBMARKUP 0A  TPS 59486 CC 0P  OTH 0A"

I need "8" (OVDPCT 8P) from this string.

Number always follow OVDPCT and precede with a P.

This 8 may be 10,12 etc means any number.

How can i by using c#.?

2
  • 1
    What's the pattern? Does the number always follow OVDPCT and precede a P? Or is it always the 5th string? Also, what solutions have you tried so far? Commented Aug 1, 2013 at 11:33
  • @mart1n yes always follow OVDPCT and precede with p Commented Aug 1, 2013 at 11:35

5 Answers 5

2

How many different variants are we talking about?

If it's always OVDPCT *P then the pattern can be:

.*OVDPCT (\d+)P.*

You can use it like this:

Match match = Regex.Match(str,@".*OVDPCT (\d+)P.*");
int num = int.Parse(match.Groups[1].Value);

Note: I'm being very rough here, you'd probably want to check match.Success and also use int.TryParse.

Sign up to request clarification or add additional context in comments.

1 Comment

I think that the reason why the OP is asking this question is because there is a small bug in your code: group instead of groups
2

So you can use a regular expression to do that

var match = System.Text.RegularExpressions.Regex.Match(str, "OVDPCT (?<Number>\\d+)P", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

if(match.Success)
{
    var number = match.Groups["Number"].Value;
}

But this line seems like an data base record isn't it?

2 Comments

Your pattern seems to need a heading "@".
or "\\" if you prefer :)
0

This should work then:

.*?OVDPCT (\d+)P.*

Comments

0

\d+ is the regex for an integer number. So

resultString = Regex.Match(subjectString, @"\d+").Value;

will give you that number as a string. Int32.Parse(resultString) will then give you the number.

Comments

0

Excuse the scrappy code but something like this:

var str = "USD  SBFARE 4067.71 OVDPCT 8P SBMARKUP 0A  TPS 59486 CC 0P  OTH 0A";

var strAsArray = str.Split(" ".ToArray(), StringSplitOptions.RemoveEmptyEntries);

var subject = strAsArray[4].Trim(); // assuming fifth element

var value = new Regex("^[0-9]+").Match(subject).Value;

Console.WriteLine("Found: ", value);

3 Comments

Why not just use a regex on the whole thing rather than just the final part to check for a number? Seems a little inefficient.
Because there are other numbers that were not of interest in the OP - at least that's how I read it
...although I've now seen the amended OP and I agree that this is not efficient given that the input string is more consistent than originally described!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.