Regular expression in exact match

Hi,
Please let me know how do i find an exact match within a string using Regular expression,
var str1:String = "s1 + s2 + sf_s1 + s1 - s2";
var replceableStr:String = "s1";
var reggular:RegExp = /\s+(s1)\s+/gi;
var str2:String;
str2 = str1.replace(reggular,"format");
i want only s1 to be replaced with format but sf_s1 should not be replaced, please let me know which Reg exp to use
Expected output: format + s2 +sf_s1 + format -s2

Odd, though. I thought regex wouldn't pick upthe
\n unless you explicitly told it to with DOTALL or
MULTILINE or (?s) or (?n).
I thought "String.matches" matched the wholestring.
So, since the string had a newline, it didn'tmatch.
It does.Ah, that would explain it then.

Similar Messages

  • Regular expressions and string matching

    Hi everyone,
    Here is my problem, I have a partially decrypted piece string which would appear something like.
    Partially deycrpted:     the?anage??esideshe?e
    Plain text:          themanagerresideshere
    So you can see that there are a few letter missing from the decryped text. What I am trying to do it insert spaces into the string so that I get:
                        The ?anage? ?esides he?e
    I have a method which splits up the string in substrings of varying lengths and then compares the substring with a word from a dictionary (implemented as an arraylist) and then inserts a space.
    The problem is that my function does not find the words in the dictionary because my string is only partially decryped.
         Eg:     ?anage? is not stored in the dictionary, but the word �manager� is.
    So my question is, is there a way to build a regular expression which would match the partially decrypted text with a word from a dictionary (ie - ?anage? is recognised and �manager� from the dictionary).

    I wrote the following method in order to test the matching using . in my regular expression.
    public void getWords(int y)
    int x = 0;
    for(y=y; y < buff.length(); y++){
    String strToCompare = buff.substring(x,y); //where buff holds the partially decrypted text
    x++;
    Pattern p = Pattern.compile(strToCompare);
    for(int z = 0; z < dict.size(); z++){
    String str = (String) dict.get(z); //where dict hold all the words in the dictionary
    Matcher m = p.matcher(str);
    if(m.matches()){
    System.out.println(str);
    System.out.println(strToCompare);
    // System.out.println(buff);
    If I run the method where my parameter = 12, I am given the following output.
    aestheticism
    aestheti.is.
    demographics
    de.o.ra.....
    Which suggests that the method is working correctly.
    However, after running for a short time, the method cuts and gives me the error:
    PatternSyntaxException:
    Null(in java.util.regex.Pattern).
    Does anyone know why this would occur?

  • Regular expressions and limiting matched input

    Hi everyone :) I am trying to put together a regular expression that matches strings that contain elements of the form;
    {<some text>}
    However, each piece of text may contain multiple embedded instances of this pattern. I want to ensure that I am always getting the first (or outermost) instance.
    So, if I had;
    {OneStart}{TwoStart}{TwoEnd}{OneEnd}
    I want to make sure that I get 'One' first and 'Two' second. So I have to place a stipulation in my regular expression to match this pattern only if it has not located the patten previously.
    At the moment, I have this -
    ([^\\{]*?)(\\{TagStart\\})(.*?)(\\{TagEnd\\})(.*)
    What I think that I have to do is modify the first capture group '([^\\{]*?)' which at the moment only does not match if a preceding '{' is found to match only if a preceding '{<text>}' sequence is not found.
    Anyone got any idea how to do this?
    Thanks in advance.
    Ben

    Doesn't it work anyway, since you're using greedy operators? If not, won't it work if you remove the .* at the end and use find() rather than matches()? And finally, what's the (.*?) supposed to match? Looks to me like that should be .*

  • SQL Injection and Java Regular Expression: How to match words?

    Dear friends,
    I am handling sql injection attack to our application with java regular expression. I used it to match that if there are malicious characters or key words injected into the parameter value.
    The denied characters and key words can be " ' ", " ; ", "insert", "delete" and so on. The expression I write is String pattern_str="('|;|insert|delete)+".
    I know it is not correct. It could not be used to only match the whole word insert or delete. Each character in the two words can be matched and it is not what I want. Do you have any idea to only match the whole word?
    Thanks,
    Ricky
    Edited by: Ricky Ru on 28/04/2011 02:29

    Avoid dynamic sql, avoid string concatenation and use bind variables and the risk is negligible.

  • Regular expression and pattern matching/replacing

    I have a list of key words. It has around 1000 key word now but can grow to 5000 keywords.
    My web application displays lot of texts which are stored in the database. My requirement is to scan each text for the occurance of any of the above keywords. If any keyword is present I have to replace that with some custom values, before showing it to the user.
    I was thinking of using using regular expression for replacing the keyword in the text using matcher.replaceAll method as follows:
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);
    String output = matcher.replaceAll(replacementStr);
    But My pattern string will have around 5000 keywords with the 'OR' Logical Operator like- keyword1| keyword2 I keyword3 | ..........
    Will such a big pattern string adversly affect the performance? What can I do to speed up the performance? (Since my keyword list is not static i would prefer to do the replacement just before showing the text to the user)
    Any suggestions are most welcome.

    I don't think a pure regex approach would be that slow, but it would be a maintenance nightmare. I think a combined regex/table-lookup approach would be best: use a regex to identify potential keywords, then look them up in the table to confirm. For instance, to find all Java keywords you could use the regex "\\b[a-z]{2,12}+\\b" to filter out anything that can't possibility be a keyword.
    What are you going to replace the keywords with? Will it vary depending on which keyword is found? If so, you'll have to use a table--and you won't be able to use the replaceAll method, because it can't handle dynamically generated replacement values. You would have to use the lower-level appendReplacement and appendTail method instead.

  • Match Regular Expression does not match what Match Pattern does

    I have read through a lot of posts about how Match Pattern does not match what Match Regular Expression will due to not processing some characters.
    However, I found a problem with the other way. A simple Reg-Ex that works in Match Pattern but not Match Regular Expression.
    What I have here is just an example. I want to use Match Regular Expression so I can specify some sub-matches.
    The reg-ex is for: one or more non-numeric characters, a space, one or more numeric characters. At the start of the string.
    How can I get this working in Match Regular Expression? I am working in LabVIEW 2010f2 32 bit. Here is the code snippet and the results:
    Rob
    Solved!
    Go to Solution.

    Robert Cole wrote:
    I think I prefer the ~ for negation since ^ is also used for beginning of the string. But we work with what we have.
    Let me offer you a tip and perhaps defend the honor of the regex a little bit.  One of my favorite features of regexes is the ability to specify character classes (and their negation).  One of the reasons I have to think about the ~ versus ^ is that I rarely use ^ in a regex alternative. 
    Some examples:
    [0-9] = \d (digit)
    [^0-9] = \D (not a digit)
    The equivalent regex for your case is: \D+ \d+

  • Regular expression doesn't match

    Hello, I'm trying to match a String with this content (without the quotes):
    "83.107.84.188"
    whith the next regular expression (without quotes again):
    "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"
    I think that all is OK, but the call to String.matches(regularExpression) returns false. What I'm doing wrong?
    Thanks in advance.
    Jorge.

    Odd, though. I thought regex wouldn't pick upthe
    \n unless you explicitly told it to with DOTALL or
    MULTILINE or (?s) or (?n).
    I thought "String.matches" matched the wholestring.
    So, since the string had a newline, it didn'tmatch.
    It does.Ah, that would explain it then.

  • Regular expression: how to match "[somestuff]"?

    I have a problem with the following code.
    I meant to catch "[fm1,-]". But I got "[fm1,-] funder [fm2,-] of our country. [sn8,s-]" instead.
    import java.util.*;
    import java.util.regex.*;
    public class regPractice {
    public static void main(String[] args) {
    String s="<TITLE Getting to Know> I hope suitabe [fm1,-] funder [fm2,-] of our country. [sn8,s-]";
    Pattern p=Pattern.compile("\\[(.*)\\]");
    Matcher m=p.matcher(s);
    if (m.find() ){
    System.out.println(m.group(0) ) ;
    }else{
    System.out.println("Nothing");
    }

    Regular expressions are greedy - that is (.*) will grab as much as it
    possibly can before a ]. Hence you see what you see.
    What you want is a reluctant quantifier, in this case (.*?)
    These grab as little as they possibly can. The parentheses are also
    not needed in your example, but you may want group(1) for some
    other reason.
    So we end up with:import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class regPractice {
        public static void main(String[] args) {
            String s = "<TITLE Getting to Know> I hope suitabe [fm1,-] funder [fm2,-] of our country. [sn8,s-]";
            Pattern p = Pattern.compile("\\[(.*?)\\]");
            Matcher m = p.matcher(s);
            if (m.find()) {
                System.out.println(m.group(0));
            } else {
                System.out.println("Nothing");
    }which gives the desired output.
    The different types of quantifier are described here:
    http://java.sun.com/docs/books/tutorial/extra/regex/quant.html

  • Regular expression help for matching numbers

    Hi,
    I want a exact match of either 9 digits or 12 digits, my query should give "No Match Found" as the input value is actually 10 digit
    select case when regexp_like(regexp_replace( ' 123 4567 890', ' ' ), '^([0-9]{9})|([0-9]{12})$')
    then 'Match Found'
    else 'No Match Found'
    end as test
    from dual;
    Need help, as I must be doing something very basic thing, wrong.
    Regards,
    Ash

    Remove 2 brackets:
    SQL> select case when regexp_like(regexp_replace( ' 123 4567 890', ' ' ), '^([0-9]{9}|[0-9]{12})$')
      2  then 'Match Found'
      3  else 'No Match Found'
      4  end as test
      5  from dual;
    TEST
    No Match Found
    SQL> select case when regexp_like(regexp_replace( ' 123 4567 89', ' ' ), '^([0-9]{9}|[0-9]{12})$')
      2  then 'Match Found'
      3  else 'No Match Found'
      4  end as test
      5  from dual;
    TEST
    Match Found
    SQL>

  • An additional question about regular expressions with String.matches

    does the String.matches() method match expressions when some substring of the String matches, or does it have to match the entire String? So, if i have the String "123ABC", and i ask to match "1 or more letters" will it fail because there are non-letters in the String, but then pass if i add "1 or more letters AND 1 or more digits"? so, in the latter every character in the String is accounted for in the search, as opposed to the first. Is that correct, or are there ways to JUST match some substring in the String instead of the whole thing? i WILL make some examples too... but does that make sense?

    It has to match the whole String. Use Matcher.find() to match on just a sub-string()

  • Regular expression: multiple possible matches, find all?

    Hi, I'm looking over something I'm afraid, the solution to my problem will probably be simple :(
    Consider the input string "something aname bname something"
    I have a list of other strings that might occur in the string:
    "aname"
    "aname bname"
    I want to know if any of the strings in the list occurs in the input string, possibly both.
    For this, I created the pattern "(?i)(aname)|(aname bname)(?i)"
    With a Matcher, it will only match the "aname", while I want to find both the "aname" and the "aname bname".
    Reversing the pattern, "(?i)(aname bname)|(aname)(?i)", it will only find "aname bname", and not the single "aname".
    I cannot really create a very sofisticated pattern such as "(aname( bname)?)", since the list of strings comes from a database. Creating a very nice pattern by looking at the possible matcher strings before compiling the pattern is not really a clean solution.
    Again: what is my at-this-point-non-functional-brain missing? Thanx!

    Thanks for the link. Of course I have read the manual, I guess there is something wrong with my eyes because I don't immediatly see the answer. Last weekend I already ordered new glasses, but they take three to four weeks to deliver my new glasses. Could you in the mean time point me to the exact place I should look?
    In all seriousness, I already tried the Matcher. It's the pattern itself that causes it to match only the first alternative in the list of groups in that pattern. I did read the Pattern manual here.
    My test code:          String input = "something aname bname";
              String match1 = "aname";
              String match2 = "aname bname";
              String quotedPattern = "(?i)(" + Pattern.quote(match1) + ")|(" + Pattern.quote(match2) + ")";
              System.out.println(quotedPattern);
              Pattern p = Pattern.compile(quotedPattern);
              Matcher m = p.matcher(input);
              while (m.find()) {
                   for (int i = 0; i < m.groupCount() + 1; i++) {
                        System.out.println("Group " + i + ":\t" + m.group(i));
              }Outputs:
    (?i)(\Qaname\E)|(\Qaname bname\E)
    Group 0:     aname
    Group 1:     aname
    Group 2:     null
    The last matching group should also match in my opinion. If I turn the pattern around, i.e. first "aname bname" and then "aname", it will still only find "aname bname" and not "aname", which would also match.
    Thanks again

  • Regular expression-- How to match whole word

    I use java.util.regex in my case,
    my problem is following:
    here is a sentence: "oRs As ordoRs"
    i use this pattern: (?!\w)oRs(?<!\w)
    the first word oRs should match, but why the third word also match?
    Maybe my problem also could be scribled as following:
    How to match whole word?

    here is a sentence: "oRs As ordoRs"
    i use this pattern: (?!\w)oRs(?<!\w)
    the first word oRs should match, but why the third
    word also match?What's even more interesting, there should be no matches at all! Just because the pattern is inherently inconsistent:
    the (?!\w) requires the next char to be a non-letter, but
    at the same time this char is reqired to be a letter 'o'.
    The same thing in the end: the last char should be 's' but not a letter. So the pattern must match nothing.
    Maybe my problem also could be scribled as following:
    How to match whole word?It's simple, use word boundaries - either directed ( "\<" and
    "\>") or undirected ("\b").
    The word pattern will look like "\b\w+\b" or "\<\w+\>"
    Test it here
    http://jregex.sourceforge.net/demoapp.html

  • [Regular Expressions] Saving a variable number of matches

    I'm stuck with the following problem and I don't seem to be able to solve without lots of ifs and else's.
    I've got a program that you can pass patterns as parameters to. The program receives patterns as one single string.
    The string could look like this:
    a:i:foo r::bar t:ei:bark
    or like this:
    a:i:foo
    What I'm hinting at is that the string comprises of several parts of the same structure. Each structure can be matched and saved with:
    ([art]:[ei]{0,2}:.*)
    Now I want my regular expression able to match all the occurences without checking the string containing the pattern for something that could indicate the number of structures inside it. The following does not seem to work:
    ([art]:[ei]{0,2}:.*)+
    So now I'm looking for something that would match one or more occurence of the structure and save it for future use.
    I'd be really happy if someone could help me out here
    Last edited by n0stradamus (2012-05-03 20:27:02)

    Procyon wrote:
    --> echo "a:i:foo r::bar t:ei:bark" | sed 's/\([art]:[ei]\{0,2\}:[^ ]*\)/1/'
    1 r::bar t:ei:bark
    --> echo "a:i:foo r::bar t:ei:bark" | sed 's/\([art]:[ei]\{0,2\}:[^ ]*\)/1/g'
    1 1 1
    If [^ ]* is not usable (spaces are allowed arbitrarily), you need a non-greedy .* and non-consuming look-ahead of " [art]:"
    In python's re module, this is .*?(?=( [art]:|$))
    >>> import re
    >>> m=re.findall("([art]:[ei]{0,2}:.*?(?=( [art]:|$)))","a:i:foo r::bar t:ei:bark")
    >>> print(m)
    [('a:i:foo', ' r:'), ('r::bar', ' t:'), ('t:ei:bark', '')]
    Exactly what I was looking for! I didn't know that you could specify .* to stop at a certain sequence of characters.
    Could you please point me to some materials where I can read up on the topic?
    Back to the regex: It works finde in Python, but sadly that is not the language I'm using
    The program I need this for is written in C and until now the regex functions from glibc worked fine for me.
    Have I missed a function similar to re.findall in glibc?

  • Regular Expression Character Sets with Pattern and Matcher

    Hi,
    I am a little bit confused about a regular expressions I am writing, it works in other languages but not in Java.
    The regular expressions is to match LaTeX commands from a file, and is as follows:
    \\begin{command}([.|\n\r\s]*)\\end{command}
    This does not work in Java but does in PHP, C, etc...
    The part that is strange is the . character. If placed as .* it works but if placed as [.]* it doesnt. Does this mean that . cannot be placed in a character range in Java?
    Any help very much appreciated.
    Kind Regards
    Paul Bain

    In PHP it seems that the "." still works as a all character operator inside character classes.
    The regular expression posted did not work, but it does if I do:
    \\begin{command}((.|[\n\r\s])*)?\\end{command}
    Basically what I'm trying to match is a block of LaTeX, so the \\begin{command} and \\end{command} in LaTeX, not regex, although the \\ is a single one in LaTeX. I basically want to match any block which starts with one of those and ends in the end command. so really the regular expression that counts is the bit in the middle, ((.|[\n\r\s])*)?
    Am I right it saying that the "?" will prevent the engine matching the first and last \\bein and \\end in the following example:
    \\begin{command}
    some stuff
    \\end{command}
    \\begin{command}
    some stuff
    \\end{command}

  • Regular expressions in Workshop 8.1

    Hello,
    I'm posting this question here because I don't see a "jdk" subcategory in this
    newsgroup and it might be problem peculiar to Workshop.
    I'm trying to use the Pattern and Matcher classes in java.util.regex (JDK 1.4.2)
    in BEA Workshop 8.1, but I'm getting "ERROR: Unknown escape code" (red squiggly
    line appears under the regex and this message is the screen tip) whenever I try
    to use the backslash to escape a special character in the Pattern.compile() and
    the Pattern.matches() methods.
    For example, it doesn't allow "\d" to mean "any digit". For this particular one,
    I can get around the problem by specifying "[0-9]", but in the case of the period
    character, I'm stuck. I cannot use "\." However, the JDK API doc (http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html)
    says the backslash is to be used for this purpose, if I'm reading it correctly.
    Is this a problem with Workshop, and is there a workaround? I need to specify
    that I require one and exactly one period.
    Any help would be most appreciated!
    Thanks.

    Yes, I had read the Java doc, but I guess I hadn't fully understood it. Now I
    do! Thanks!!
    David
    Josh Eckels <[email protected]> wrote:
    This isn't particular to Workshop, but you'll need to use two
    backslashes in your source code. Inside a string, backslash is used to
    escape the next character so that you can enter special characters like
    newlines ('\n'), tabs ('\t'), etc.
    So, in order to enter a backslash character into your string, you need
    to escape it, like '\\'.
    There's a small section on this in the java.util.regex.Pattern JavaDoc,
    under the "Backslashes, escapes, and quoting" header:
    Backslashes within string literals in Java source code are interpreted
    as required by the Java Language Specification as either Unicode escapes
    or other character escapes. It is therefore necessary to double
    backslashes in string literals that represent regular expressions to
    protect them from interpretation by the Java bytecode compiler. The
    string literal "\b", for example, matches a single backspace character
    when interpreted as a regular expression, while "\\b" matches a word
    boundary. The string literal "\(hello\)" is illegal and leads to a
    compile-time error; in order to match the string (hello) the string
    literal "\\(hello\\)" must be used.
    Josh
    David Chang wrote:
    Hello,
    I'm posting this question here because I don't see a "jdk" subcategoryin this
    newsgroup and it might be problem peculiar to Workshop.
    I'm trying to use the Pattern and Matcher classes in java.util.regex(JDK 1.4.2)
    in BEA Workshop 8.1, but I'm getting "ERROR: Unknown escape code" (redsquiggly
    line appears under the regex and this message is the screen tip) wheneverI try
    to use the backslash to escape a special character in the Pattern.compile()and
    the Pattern.matches() methods.
    For example, it doesn't allow "\d" to mean "any digit". For this particularone,
    I can get around the problem by specifying "[0-9]", but in the caseof the period
    character, I'm stuck. I cannot use "\." However, the JDK API doc
    (http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html)
    says the backslash is to be used for this purpose, if I'm reading itcorrectly.
    Is this a problem with Workshop, and is there a workaround? I needto specify
    that I require one and exactly one period.
    Any help would be most appreciated!
    Thanks.

Maybe you are looking for

  • Http server code 503 reason Service Unavailable explanation Service Unavail

    Hi all I am trying to send data to a HTTP SITE. I am getting the following error. Could somebody guide me how to solve this. <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> - <!--  Call Adapter   --> - <SAP:Error xmlns:SAP="http://sap.com/xi

  • MY AIRPORT TIME CAPSULTE WONT CONNECT TO THE INTERNET

    i bought a new airport time capsule.  connected it to my modem/router via ethernet cable.  plugged it in, and cant get it setup from there.  the airport utility is saying it's not connected.  help would greatly be appreciated!

  • Need user exit or BADI for NMM1

    Hi, I need user exit/BADI  for transaction NMM1. We need to know the material status of material to determine whether to send a Reservation or PR. Presently it is determining depending on material type . Regards, Sekhar Raju.

  • Webdispatcher with load-balancing and local icm configuration

    Dear all, we have a webdispatcher in place to load-balance the requests to our three application servers (ABAP). The webdispatcher has a hostname that is resolved by the DNS. The application servers use local hostnames that can't be resolved in our i

  • Two EHP1 in parallel on same host....Please reply ASAP

    Hi, We have NW BI 7.0 with two different SIDs. The ABAP is AW1 and J2EE is JW1. They are on the same host. They are ABAP and Portal for our BW system and integrated to each other. Can we run both enhance package installation in parallel as they are o