2

I have a string as:

 string subjectString = @"(((43*('\\uth\Hgh.Green.two.190ITY.PCV')*9.8)/100000+('VBNJK.PVI.10JK.PCV'))*('ASFGED.Height Density.1JKHB01.PCV')/476)";

My expected output is:

Hgh.Green.two.190ITY.PCV
VBNJK.PVI.10JK.PCV
ASFGED.Height Density.1JKHB01.PCV

Here's what I have tried:

 Regex regexObj = new Regex(@"'[^\\]*.PCV");
 Match matchResults = regexObj.Match(subjectString);
 string val = matchResults.Value;

This works when the input string is :"@"(((43*('\\uth\Hgh.Green.two.190ITY.PCV')*9.8)/100000+"; but when the string grows and the number of substrings to be extracted is more than 1 , I am getting undesired results .

How do I extract three substrings from the original string?

1 Answer 1

2

It seems you want to match word and . chars before .PCV.

Use

[\w\s.]*\.PCV

See the regex demo

To force at least 1 word char at the start use

\w[\w\s.]*\.PCV

Optionally, if needed, add a word boundary at the start: @"\b\w[\w\s.]*\.PCV".

To force \w match only ASCII letters and digits (and _) compile the regex object with RegexOptions.ECMAScript option.

Here,

  • \w - matches any letter, digit or _
  • [\w\s.]* - matches 0+ whitespace, word or/and . chars
  • \. - a literal .
  • PCV - a PCV substring.

Sample usage:

var results = Regex.Matches(str, @"\w[\w\s.]*\.PCV")
    .Cast<Match>()
    .Select(m=>m.Value)
    .ToList();
Sign up to request clarification or add additional context in comments.

5 Comments

I think you need to escape the '.' also, like this: [\w\.]*\.PCV
@BG100: No, inside a character class only -, ], \, ^ need escaping. And ] needs no escaping if it is the first char, and ^ needs no escaping if it is not the first char, and - does not need escaping if it is the first/last char in the character class.
Ah! I didn't realise that! Just tried it and you're right... :)
@WiktorStribiżew : The results[2] is :"Density.1JKHB01.PCV" but I need "ASFGED.Height Density.1JKHB01.PCV" although the other two results are correct.
Add a whitespace to the class - @"\w[\w\s.]*\.PCV" then. Else, please precise the requirements. I still would follow the whitelisting approach here unless you are sure about what the delimiter pattern should look like.

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.