Using Regular Expressions To Parse Functions

free web hosting
Free Web Hosting > Computers & Tech > Programming > Programming General > C# .NET

Using Regular Expressions To Parse Functions

turbopowerdmaxsteel
I have a hierarchy of functions represented as something like:-

@BeforeText(@AfterText(@ReadURL('http://www.quotationspage.com/quote/1.html')@,'<dt>',True)@,'</dt>',True)@

Each of the functions follow the format @FunctionName(<ParamString>)@. The ParamString itself can be composed of a string, a number or a boolean value. For example:-

@AfterText('String', "st", True)@ - This function returns the portion of text following the specified substring. It is composed of three parameters. First one is the string being worked on, second is the substring being sought and the third parameter denotes whether to Ignore case.

The above code will result in an output of ring.

Trouble starts with function nesting. The following example should give the output so.

@BeforeText(@AfterText('Microsoft', "Micro", True)@, "ft", True)@

This kind of nesting should be possible to arbitrary levels. I can do this using Loops and Conditional Branching statements. But, I would rather use Regular Expressions and in the process learn some more nuances of .NET's Regular Expression support.

Classes for evaluating the functions have been designed. What I need to do is parse the functions from the deepest of levels just as the programming languages do, execute it and use the resulting output as parameters to outer level functions. But I am not sure where to begin. Anybody care to give a head start?

 

 

 


Reply

faulty.lee
Why don't you consider using .net scripting or powershell, instead of cracking your head to reinvent the wheel. For .net scripting, the script itself is plain .net, be it VB.Net or C#. The main thing is to use System.CodeDom.Compiler.ICodeCompiler to compile and run the code on the fly. Windows Powershell http://www.microsoft.com/windowsserver2003...ll/default.mspx
It's also relying on .net. But it's scripting engine is much more powerful, and suited to run as an console or scripted.


Reply

turbopowerdmaxsteel
I have tried my hands on the ICodeCompiler interface. It forms a part of the package I am building for Pika Bot. But, these functions have got to be written in this custom language and regular expressions seemed to be the best option. I could, however, convert these functions into VB or C# representations and execute the code using the ICodeCompiler interface.

Reply

turbopowerdmaxsteel
Given below is a simplistic code that represents the function evaluation method. Codes irrelevant to the problem have been abstracted to avoid cluttering.

CODE
public static string Substitute(string Message)
{
    string Pat = @"@(?<name>[a-z0-9]+)\((?<paramstring>.*)\)@";
    Match M = Regex.Match(Message, Pat, RegexOptions.IgnoreCase | RegexOptions.Singleline);

    if (M.Success)
    {
        // BEGIN Parameter determination Code

        // END Parameter determination Code

        // Substitute Parameters, incase they contain functions. (Nested Functions)
        for(int i = 0; i < Params.Length; i++)
        {
            Params[i] = Substitute(Params[i]);
        }

        // Pre & Post variables contain the strings which are before and after the matched text.
        // Func is an object of the appropriate function class.
        // The Parameters are added to it after they are substituted.
        Message = Pre + Func.Invoke() + Post;
    }
    return Message;
}


The pattern matches the outermost function (using .* in the paramstring) and thus allows nested functions to be matched in the next recursions of the function. A lot of code exists between the // BEGIN Parameter determination Code and // END Parameter determination Code blocks. This splits the ParamString using , to determine the parameters and then combines invalid string entries (incase the , is contained inside a string parameter). The loop iterates through all the parameters calling the function itself for all the parameters. This takes care of nested functions. The object Func returns the result obtained from evaluating the function. For example @Log10(100)@ will result in 2. Pre & Post contain the strings before and after the matched text. In the input ABC@Rnd(1,100)@DEF, ABC is Pre and DEF is Post.

Consider the following Input:-

@BeforeText(@AfterText('School','S')@,'l')@

In the first call to the Substitute function, the pattern matches the whole input: @BeforeText(@AfterText('School','S')@,'l')@. Here, BeforeText is the name sub-group while @AfterText('School','S')@,'l' is the paramstring sub-group. The next recursive call to the substitution function passes the input: @AfterText('School','S')@.

The problem now is that multiple functions at the same level cannot be evaluated.

@Log10(0)@ Some Intermediate Text @Log(0)@

The Pattern matches the entire message - @Log10(0)@ Some Intermediate Text @Log(0)@. But, what I want it to do is match @Log10(0)@ and @Log(0)@ seperately. Excluding the symbols @ ( ) from the paramstring will not work as that would disable nested functions to be evaluated. I am wondering if there is something like recursive pattern matching in .NET and will it be able to aid in this matter.

 

 

 


Reply

faulty.lee
I'm not that good with regex. I do have a suggestion, maybe you can count for matching '@(' and ')@'. Say for every '@(' you increment the counter, then for every ')@' you decrement the counter. Like reference counting in C++. When counter is 0, you need to look for the next function, instead of skipping it. Get the last position/index of the last matching '@(' ')@' pair, then can either chop off the matched set of '@( and ')@', the match the regex again, of use the match function where you can specified the starting position for matching (but you loose the regexoption).

Reply

turbopowerdmaxsteel
I would have done it that way back in the old days but ever since realizing the power of Regex, it just doesn't feel right. It is my last option, though. I have just come across some interesting ways of matching such constructs but I can't seem to get them to work. Any ideas?

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. regular expression to parse c# classes - 7.94 hr back. (1)
  2. parse string with regex - 8.43 hr back. (1)
  3. email evaluator regexp c# - 14.93 hr back. (1)
  4. vb.net parse regular expressions - 15.80 hr back. (1)
  5. parse matches regexp c# - 27.74 hr back. (1)
  6. regex parsing c class - 29.39 hr back. (1)
  7. c# recursive regular expression - 30.32 hr back. (1)
  8. regular expression parse google c# - 55.74 hr back. (1)
  9. parse functions regex - 57.85 hr back. (1)
  10. c# regex remove script tag - 64.27 hr back. (1)
  11. logic for ignoring unwanted keywords c# - 69.89 hr back. (1)
  12. parse html c# regex - 70.32 hr back. (3)
  13. c# removing illegal characters from filename with regex - 78.12 hr back. (1)
  14. c# removing illegal characters from filename regex - 78.15 hr back. (1)
Similar Topics

Keywords : regular, expressions, parse, functions

  1. Parse PHP And Display PHP Generated Output
    How do you display your php output? (8)
  2. Regular Expressions
    (6)
    In PHP and many other programming languages, I have heard of this powerful syntax called RegEx, or
    regular expressions. It allows you to find strings that match a certain pattern. I had to use a
    regex expression to search for a specific string of text within a block of text once, and someone
    told me to use a regular expression. The example that they wrote worked, although it was extremely
    confusing and I didn't know what it meant. http://www.regular-expressions.info/ gives a great
    tutorial on regular expressions, the syntax and stuff. I'm not sure if this is ....
  3. Php: Lesson #3;functions
    PHP. (0)
    Well, the last lesson was on If...Else statements, this one will be on Functions. Things you need
    to know 1.Basic PHP(Lesson 1) 2.I only speak English, sorry. So, everything will be in English
    terms. 3.I only put the stuff in quotes to be more organized. xD Lesson #3; Functions!
    Questions & Answers Q1.What is a function? A1.A function is code that we can access at any time,
    such as the e-mail function; mailto(email@something.com). Q2.Why use functions? A2.Would you rather
    use CODE <?php lots and lots of code more code more and more code ?&#....
  4. Creating Dll With Delphi
    show how to pass functions and procedures in DELPHI (0)
    First of all, I'd like to apologise because my English is not tha good. Well, It's a very
    popular doubt. like How can I use a DLL? How can I create one? What is it for? So, DLL or Dynamic
    Link Libraries, allows a set of functions developed in one especific programmer language to be used
    for softwares developed in other language. For example, you can create a DLL in DELPHI and use it
    with a software developed in C++ for example. So, let's get started: Select the Item NEW in the
    menu FILE to show the dialog box NEW ITEMS. Now select DLL and OK to generate ....
  5. Random With Functions?
    (4)
    Hey! Is it possible to use a random script on functions. Lets say I have created three
    functions (Items that a user will win if he defeates a monster). One function is a function named
    shield() and another function is named sword() and a third function is named helmet(). Now when a
    player defeates a monster, he must be awarded. So.. How can I randomize what item he should get?
    something like CODE rand(sheild(), sword(), helmet()); or?
    Thanks //Feelay....
  6. Regular Expressions Not Matching
    (4)
    Hi All, I am using Regular Expressions in VB.NET to find illegal filename characters in a string.
    The user enters and name, and it then saves the file with that name. I just need to make sure that
    the filename doesn't contain illegal filename characters. The characters are / \ : ?
    " | (is there any others?) I am using the following regex at the moment, but it doesn't
    seem to be picking up backslashes. CODE Dim myRegex As New
    System.Text.RegularExpressions.Regex("[\/:?'=<>|]")
    Every other charact....
  7. Filtering Out Unwanted Junk Mail Using Regular Expression.
    Use this Regular Expression with the cPanel email filter to limit your (0)
    I'm so irritated with the amount of spam I get on the email accounts I have hosted at AstaHost.
    It isn't the servers fault that I get so much junk mail! It wouldn't be so bad but my
    junk mail filter on my home system doesn't scan IMAP accounts which I use since my email client
    won't separate POP3 accounts properly. So I finally got to the point I had to do
    something! I'm getting about 25 junk mail messages a day spread over 5 different email
    accounts. If I go a few days without checking my email, I have a lot of work to do to clean ....
  8. The Absolute Bare Minimum Every Programmer Should Know About Regular Expressions
    (1)
    Well, the title says it all and I really don't have anything to add to that, except to say that
    this is a really, really powerful technology that is very pervasive in many programming as well as
    scripting languages and as well in mainstream database products. I really recommend you put in the
    time and effort to learn regular expressions, they are power tools that are going to open for you a
    whole new world of text processing possibilities. Link:
    http://immike.net/blog/2007/04/06/the-abso...ar-expressions/ ....
  9. C# Tutorial : Lesson 8 - Functions/methods
    (0)
    The programming model has gone through many refinements, each change improving upon the model. One
    of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these
    are fragments of code within a program. They offer the following advantages:- Reduction of code
    duplication by offering re-usability Simplifying program logic by decomposing the program into
    smaller blocks Improving readability of the program Why do we need functions?
    Consider the following program:- CODE using System; namespace ConsoleApplication1 { ....
  10. Javascript Show / Hide Functions
    need some fine-tuning (3)
    Searching before posting my topic, i found this very helpful post. Javascript show + hide
    However, I'm still muddling around trying to fine tune it, and since i'm no good at coding,
    I'd appreciate any help. Using that example, how do I get the div text to be hidden on loading,
    rather than showing it all at page load. Also, is there a way to have the text change when clicked?
    so that for example, it would say "expand" when it's the small amount of text, and "collapse"
    when it's the full text? ....
  11. How To Remove Query String Using Regular Expressions
    (4)
    Hi, I'm a complete newbie using regular expressions and what i want to do is to remove all the
    parameters of the query string of any url using regular expressions, how can i do this? For example
    if i have some urls like these: http://www.domain.com/file1.php?var1=value1&var2=value2
    http://www.domain.com/file2.php?var1=value1&var2=value2
    http://www.domain.com/file3.php?var1=value1&var2=value2 I want to only get these ones:
    http://www.domain.com/file1.php http://www.domain.com/file2.php http://www.domain.com/file3.php
    If it is possible please post no....
  12. Writing Functions In PHP
    Turn Your PHP Script Into A Reusable PHP Function (6)
    Well, it has been a while since I offered a tutorial here at AstaHost. Most of my creativity has
    gone toward my new website, Handy PHP . The website is just getting started and it is hard to post
    potential content for my website here instead of there. The purpose of this tutorial is to show you
    how to convert a standard PHP script into a reusable PHP function. It is funny, because this
    tutorial is very similar in nature to the very first tutorial I wrote here. Rapid HTML code
    generation using simple PHP would be a good topic to read with this tutorial. Before we....
  13. C++: Basic Classes
    classes, objects, access labels, members, inline functions (5)
    This tutorial assumes that you have a basic knowledge of C++. You know how to use built-in types,
    like ints, doubles, chars, etc. You should know some types that are part of the STL, like vector,
    etc. Those types that come in the STL are just C++; you can create your own types just like
    those! Non built-in types are referred to as classes . To create a class, you just use the
    keyword class , the name of the class, and curly brackets. CODE //A class named MyClass class
    MyClass { }; In fact, that is all we need to create variables, pointers, or references ....
  14. Faq Section Error
    Parse error: syntax error, unexpected '<' in /home/faqedit/ (2)
    I'm not sure if this is just me. But it's a server side parse error so should be global I
    get this error when i try to access the FAQ section Parse error: syntax error, unexpected '
    Also, i did a search to see if such error has already been reported. nothing if i use "frequently".
    Too bad i can't use "faq" as a search term.....
  15. Announcement: Importance Of Regular Site Backups !
    (18)
    This is to inform all our members that recently we've been facing a lot of hacking attempts
    from various upcoming groups - whose sole purpose seems to be defacing our members' sites. In
    most cases it's just a minor botheration though I've no clue what they're gaining out of
    it. Pertaining to this I'd like to mention that we don't employ a server-side backup
    mechanism anymore. Long time back we used to perform weekly backup of all our members' sites -
    but this service has been discontinued for a while now owing to some conflict with t....
  16. Help: Smf Sources.php File Producing Parse Error
    unexpected T_VARIABLE, expecting ')' (5)
    I have really serious problem with SMF. Its about some stupid message whhich keeps appearing
    everytime I load the "profile" page in SMF. Here is what it says: "Parse error: parse error,
    unexpected T_VARIABLE, expecting ')' in /home/ganesh/public_html/Sources/Profile.php on line
    1814" This is source code for that "Profile.php" file. I am asking this because I relly dont know
    PHP very well, still learning. So is there an PHP coder for this problem, please help! Mods or
    admins please make this a new topic if possible. Here is the link to that profile.php fi....
  17. Calling Of Functions Between Mulitple External Javascript Files
    How do I use an external script to call a function from another script (2)
    I have a page that requires many Javascript functions. In order to make the coding easier to read
    and edit, I decided to seperate them into 3 Javascript files. Two files will each do a specific job.
    One file will have the shared functions that both other 2 files will need to use. They are all
    linked to a page using three <script> tags. The difficult part is that after the page calls a
    function in one of the special code files, that Javascript file will need to call the functions
    located in the common Javascript file. The file will call several functions, and it will....
  18. Any Active & Regular Vietnamese Member At Astahost ?
    (3)
    Hey guys, Do we have any active and regular Vietnamese member on board ? I'm looking for
    someone who's well conversant in both Vietnamese and English. Errrr.. the things that I've
    landed up with a real cute vietnamese girlfriend while I was on my Cambodia-Vietnam trip some 2
    weeks back. Problem is that she understands english, but speaks just about 10 words of it. When I
    was present there, face-to-face, our conversations still happened mostly owing to my immense
    patience and 6 years of hardcore training in Thailand - trying to drum stuff into the heads of ....
  19. Airtel GPRS
    Information about my not so regular Internet connection. (22)
    I use a SAMSUNG SGH-C200N handset coupled with Airtel (a GSM Service Provider in Asia) GPRS to
    connect to the internet. Here is a review about my Internet Connection - Points > By default
    Windows always shows the connection speed to an outstanding 115.6 KBps. Although, from what I have
    seen via the connection status, when downloading files from a good server, the maximum speed that I
    get is around 5 Kbps. During the peak hours, the connection's speed deteriorates and the data
    transmission becomes intermittent. Every Page (except for good ol' Google)....
  20. Google Adsense's Functions
    How does Pay per Click works? (1)
    I wanna know how the Pay-per-Click works. This is because I have put the ads up on my website. There
    are queries from the Google Search but no cash. My Google ads also have not generated money. It
    states another confusing thing: Cost-per-1000 impressions. What is that????....
  21. PHP And Texts: Need Help With PHP String Functions
    (5)
    Hey people! I'm pretty new with PHP and MySQL. I wanna have all the text on my site in
    MySQL. But i'm having trouble with the inputing from HTML-forms, like . How to i do it? Can i
    use PHP or is it better to use javascript and sorta add htmltags into the tag? I wanna make a
    texteditor where i can use bold, italic and that kinda stuff. I'm thankful for any help...
    /Jens....
  22. Multibyte-string Functions
    since server shift (1)
    Hello, I use multibyte functions to split a string by letter and I was wondering if you could turn
    them on again, because they were on before the server shift (and they are in PHP by default) and now
    I get fatal errors, when trying to use them. In the Phpinfo they don't appear at all.. I've
    been waiting for quite some time now and it is only a basic PHP-integrated feature.. Thanks, Ruben....
  23. Php Parsing Error On Smf On My Site
    Parse error: parse error, unexpected T_C (16)
    QUOTE Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING in
    /home/jeremy1/public_html/guild_forum/Sources/Subs.php on line 272 thats the error I get when
    people try to access the forums I run on my website. I've been through the code but can't
    figure out exactly whats wrong. I'm still quite new to PHP and still have a very limited
    understanding of it. All I can say for certin is that up untill around 2 p.m. PST the forums were
    working then around that time they seem to have stopped and started outputing that error message.
    If anyone c....
  24. Difference Between Starter And Regular
    Do u have to manage credits differently? (3)
    If you have the default account (30 credits) do you have to post more to keep your hosting up
    compared to the starter (10 credits)? And are credit records kept before you get hosting? Because I
    didn't know that credits were reset after you get hosting. I had 30, but was planning to
    conserve credits and went for the starter. XP Thanks.....
  25. Php : Variables Included Dont Work In Functions
    Variables from Included files dont work (4)
    Today, I came up with this strange PHP behaviour. Just wanted to know if anyone has any
    suggestions! I make a common variable/function file called config.php. I put in my generally
    used functions in it. Suppose this is my file // -----VARIABLES --- // $a=10,$b....
    // -----FUCTIONS--- // function doit() { print "A value is " . $a; } ?> Here, suppose we
    execute this file directly. Since A has a global scope, it does work perfectly. But if this same
    file is imported in another file say, mainfile.php // -----VARIABLES --- // $c,$....
  26. Megatsunamis
    Even more spectacular than regular ones (9)
    Megatsunamis Megatsunami. The word accurately describes what it means. Where tsunamis are big,
    megatsunamis break all limits. Tsunamis are regular surfing waves compared to these guys. They can
    rise up to be 200 meter high wall of water, destroying everything on its path. Time to take a closer
    look. On the subject tsunamis, Nathan posted this explanation: QUOTE In tribute to
    have died, I thought I'd post this! A tsunami is a series of huge waves that happen after an
    undersea disturbance, such as an earthquake or volcano eruption. (Tsunami is f....
  27. Php Regular Expressions
    Request For Help. (11)
    So I'm trying to learn how to pull useful content from a web page. Here's what I got so
    far: CODE <?php $filename = "http://www.forum500.com"; $html =
    file_get_contents($filename); /*
    **************************************************************** */ /*                              
                                       */ /*             Got this code @ http://www.php.net/        
             */ /*                                                                  */ /*
    ***************************************************....
  28. Regular Used Terms In The Webhosting World
    (4)
    Lets begin with some regular used terms in the webhosting world: FTP - File Transfer Protocol.
    This is the service for transferring files (also the files for your website (the .html or .htm) to
    your webhost. Some webhosts offer FTP, others don't. PHP - A server-side scripting language,
    used to generate dynamic HTML on your websites. MySQL - Open Source software for a database
    management system. This can be used for forums, and other databases on the net. Also PHP can use
    this software to make a dynamic website. Domain name - This is a text name card for a comput....
  29. Request To Upgrade
    stater to regular (1)
    hey i have posted 70 post so i am going to ask again if i can get my upgrade
    username:wannabeeaweak Cpanel username:wannabee password:****** Cpanel password:******
    email:clovis818@aol.com website being built :www.mysitesucks.tk....
  30. Need Hosting!
    upgrade to regular hosting (1)
    ok well i know that i do not have tons of good posts ok but i do have some and i need more space
    badly because i have a web site being made on this hosting and i need more space to came my web
    site. so please upgrade my hosting username:wannabeeaweak username for Cpanel:wannabee
    password:***** password for Cpanel:***** email:clovis818@aol.com please upgrade my
    hosting!!!! I NEED IT BADLY !!!!!!!!....

    1. Looking for regular, expressions, parse, functions

Searching Video's for regular, expressions, parse, functions
Similar
Parse PHP
And Display
PHP
Generated
Output - How
do you
display your
php output?
Regular
Expressions
Php: Lesson
#3;functions
- PHP.
Creating Dll
With Delphi
- show how
to pass
functions
and
procedures
in DELPHI
Random With
Functions?
Regular
Expressions
Not Matching
Filtering
Out Unwanted
Junk Mail
Using
Regular
Expression.
- Use this
Regular
Expression
with the
cPanel email
filter to
limit your
The Absolute
Bare Minimum
Every
Programmer
Should Know
About
Regular
Expressions
C# Tutorial
: Lesson 8 -
Functions/me
thods
Javascript
Show / Hide
Functions -
need some
fine-tuning
How To
Remove Query
String Using
Regular
Expressions
Writing
Functions In
PHP - Turn
Your PHP
Script Into
A Reusable
PHP Function
C++: Basic
Classes -
classes,
objects,
access
labels,
members,
inline
functions
Faq Section
Error -
Parse error:
syntax
error,
unexpected
'<
9; in
/home/faqedi
t/
Announcement
: Importance
Of Regular
Site Backups
!
Help: Smf
Sources.php
File
Producing
Parse Error
- unexpected
T_VARIABLE,
expecting
')'
Calling Of
Functions
Between
Mulitple
External
Javascript
Files - How
do I use an
external
script to
call a
function
from another
script
Any Active
&
Regular
Vietnamese
Member At
Astahost ?
Airtel GPRS
-
Information
about my not
so regular
Internet
connection.
Google
Adsense'
s Functions
- How does
Pay per
Click works?
PHP And
Texts: Need
Help With
PHP String
Functions
Multibyte-st
ring
Functions -
since server
shift
Php Parsing
Error On Smf
On My Site -
Parse error:
parse error,
unexpected
T_C
Difference
Between
Starter And
Regular - Do
u have to
manage
credits
differently?
Php :
Variables
Included
Dont Work In
Functions -
Variables
from
Included
files dont
work
Megatsunamis
- Even more
spectacular
than regular
ones
Php Regular
Expressions
- Request
For Help.
Regular Used
Terms In The
Webhosting
World
Request To
Upgrade -
stater to
regular
Need
Hosting!
- upgrade to
regular
hosting
advertisement




Using Regular Expressions To Parse Functions



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE