c# - String manipulation: How to replace a string with a specific pattern -
i've question here related string manipulation based on specific pattern. trying replace specific pattern pre-defined pattern using c#
for eg:
scenario # 1
input: substringof('xxxx', [property2]) output: [property2].contains('xxxx')
where string used within linq's where
clause.
my sol:
var key= mystring.substring(mystring.split(',')[0].length + 1, mystring.length - mystring.split(',')[0].length - 2); var value = mystring.replace("," + key, "").replace([key dictionary], [value dictionary]);
expected string: key + '.' + value.replace("('", "(\"").replace("')", "\")");
but works above scenario. generalize teh below scenario's.
scenario's:
input: [property1] == 1234 , substringof('xxxx', [property2]) , substringof('xxxx', [property3]) output: [property1] == 1234 , [property2].contains('xxxx') , [property3].contains('xxxx') input: substringof('xxxx', [property2]) , [property1] == 1234 , substringof('xxxx', [property3]) output: [property2].contains('xxxx') , [property1] == 1234 , [property3].contains('xxxx')
any appreciated. in advance!!
final solution:
var replaceregex = new regex("substringof\\(\\s*'(?<text>[^']*)'\\s*,\\s*(?<pname>[\\w\\[\\]]+)\\s*\\)"); input = replaceregex.replace(input, "${pname}.contains(\"${text}\")");
here's sample code seems work:
system.text.regularexpressions.regex replaceregex = new system.text.regularexpressions.regex("substringof\\(\\s*'(?<text>[^']*)'\\s*,\\s*(?<pname>[\\w\\[\\]]+)\\s*\\)"); string input1 = "[property1] == 1234 , substringof('xxxx', [property2]) , substringof('xx xx', [property3])"; string input2 = "substringof('xxxx', [property2]) , [property1] == 1234 , substringof('xxxx', [property3])"; string input3 = "(id > 0 , substringof('2', name))"; string output1 = replaceregex.replace(input1, "${pname}.contains('${text}')"); string output2 = replaceregex.replace(input2, "${pname}.contains('${text}')"); string output3 = replaceregex.replace(input3, "${pname}.contains('${text}')");
note added tolerance internal whitespace , made assumptions text matched. kinds of characters can included inside quotes and/or property identifiers? may need tweaked fit requirements.
edit: did proactive tweaking. changing \w* [^']* means match spaces or symbols or whatever until reaches closing quote, stop matching. little more in line standard programming languages. property name kept more restrictive: \w match letters, numbers, , underscore characters. none of substitute proper parser/lexer catch errors , identify them explicitly, might in pinch.
edit 2: updated remove requirement brackets. note tolerant: pattern match odd strings substringof('xxxx', [[property3]morestuffhere[)
because assumes [ , ] valid characters in identifier. not allow symbols or spaces, regardless of whether there brackets or not. note replacement string has changed. if don't remove square brackets (as have done in sample), end double brackets.
Comments
Post a Comment