Regular expression - variable

I need to add a piece of code in each page in a directory with some info that is specific to that directory.  There are several hundred directories and about 10,000 pages.  My plan was to search and replace all files in each directory one at a time.  Then I remembered RegEx and thought there may be a better solution.
The code I want to build off of looks like this:
<?php
setcookie("capital", "boston", time()+31536000, "/");
?>
The only variable part is the the city name (i.e. boston could be denver, tampa, miami, etc.).  This bit of text will always be a word with only letters and no spaces.I'd like to search for this code, using regular expressions to capture the variable (i.e "boston"), then replace it with the exact same code, plus add another snippet using the stored variable.
The end result should look like this:
<?php
setcookie("capital", "boston", time()+31536000, "/");
$urlcookievariable = "boston";
?>
My RegEx attempt looks like this:
SEARCH:
<?php
setcookie("capital", "[^"]*", time()+31536000, "/");
?>
REPLACE:
<?php
setcookie("capital", "[^"]*", time()+31536000, "/");
$urlcookievariable = "$1";
?>
However, it's not seeming to find the original line of code.  Since my search is working, my replace is obviously not working either.  However, with some testing on a more simple line of regex, that variable is not pasting as a variable.  It's just putting the literal symbol:  dollar sign and #1....$1, not "boston"
thanks in advance for a point in the right direction

The problem with your regex is that the original code includes metacharacters that have special meaning in a regular expression. Use this as the search value:
(setcookie\("capital", ("[^"]+"), time\(\)\+31536000, "\/"\);)
Use this as the Replace value:
$1\n$urlcookievariable = $2;

Similar Messages

  • Regular expressions with multi character separator

    I have data like the
    where |`| is the separator for distinguishing two fields of data. I am having trouble writing a regular expression to display the data correctly.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL> declare
      2  l_string varchar2 (200) :='123` 456 |`|789 10 here|`||223|`|5434|`}22|`|yes';
      3  v varchar2(40);
      4  begin
      5  v:=regexp_substr(l_string, '[^(|`|)]+', 1, 1);
      6  dbms_output.put_line(v);
      7  v:=regexp_substr(l_string, '[^(|`|)]+', 1, 2);
      8  dbms_output.put_line(v);
      9  v:=regexp_substr(l_string, '[^(|`|)]+', 1, 3);
    10  dbms_output.put_line(v);
    11  v:=regexp_substr(l_string, '[^(|`|)]+', 1, 4);
    12  dbms_output.put_line(v);
    13  v:=regexp_substr(l_string, '[^(|`|)]+', 1, 5);
    14  dbms_output.put_line(v);
    15  end;
    16  /
    123
    456
    789 10 here
    223
    5434I need it to display
    123` 456
    789 10 here
    |223
    5434|`}22
    yesI am not sure how to handle multi character separators in data using reg expressions
    Edited by: Clearance 6`- 8`` on Apr 1, 2011 3:35 PM
    Edited by: Clearance 6`- 8`` on Apr 1, 2011 3:37 PM

    Hi,
    Actually, using non-greedy matching, you can do what you want with regular expressions:
    VARIABLE     l_string     VARCHAR2 (100)
    EXEC  :l_string := '123` 456 |`|789 10 here|`||223|`|5434|`}22|`|yes'
    SELECT     LEVEL
    ,     REPLACE ( REGEXP_SUBSTR ( '|`|' || REPLACE ( :l_string
                                     , '|`|'
                                      , '|`||`|'
                                     ) || '|`|'
                        , '\|`\|.*?\|`\|'
                        , 1
                        , LEVEL
               , '|`|'
               )     AS ITEM
    FROM     dual
    CONNECT BY     LEVEL     <= 7
    ;Output:
    LEVEL ITEM
        1 123` 456
        2 789 10 here
        3 |223
        4 5434|`}22
        5 yes
        6
        7Here's how it works:
    The pattern
    ~.*?~is non-greedy ; it matches the smallest possible string that begins and ends with a '~'. So
    REGEXP_SUBSTR ('~SHALL~I~COMPARE~THEE~', '~.*?~', 1, 1) returns '~SHALL~'. However,
    REGEXP_SUBSTR ('~SHALL~I~COMPARE~THEE~', '~.*?~', 1, 2) returns '~COMPARE~'. Why not '~I~'? Because the '~' between 'SHALL' and 'I' was part of the 1st pattern, so it can't be part of the 2nd pattern. So the first thing we have to do is double the delimiters; that's what the inner REPLACE does. The we add delimiters to the beginning and end of the list. Once we've done prepared the string like that, we can use the non-greedy REGEXP_SUBSTR to bring back the delimited items, with a delimiter at either end. We don't want those delimiters, so the outer REPLACE removes them.
    I'm not sure this is any better than Sri's solution.

  • Regular Expressions and String variables

    Hi,
    I am attempting to implement a system for searching text files for regular expression matches (similar to something like TextPad, etc.).
    Looking at the regular expression API, it appears that you can only match using string variables. I just wanted to make sure this is true. Some of these files might be large and I feel uneasy about loading them into ginormous Strings. Is this the only way to do it? Can I make a String as big as I want?
    Thanks,
    -Mike

    Newlines are only a problem if you're reading the
    text line-by-line and applying the regexp to each
    line. It wouldn't catch expressions that span
    lines.
    @sabre150: your note re: CharSequence -- so what
    you're suggesting is to implement a CharSequence that
    wraps the file contents, and then use the regexps on
    the whole thing? I like the idea but it seems like
    it would only be easy to implement if the file uses a
    fixed-width character set. Or am I missing
    something...?You are correct for the most basic implementation. It is very easy to create a char sequence for fixed width character sets using RandomAccessFile. Once you go to character sets such as UTF-8 then more effort is required.
    While ever the regex is moving forward thought the CharSequence one char at a time there is no problem because one can wrap a Reader but once it backtracks then one needs random access and one will need to have a buffer. I have used a ring buffer for this which seems to work OK but of course this will not allow the regex to move to any point in the CharSequence.
    'uncle_alice' is the regex king round here so listen to him.
    :-( I should read further ahead next time!
    Message was edited by:
    sabre150
    Message was edited by:
    sabre150

  • Regular expression result into variable??

    Im dealing with log files here...i use regular expression to detect the values...how can i save these values into variable, for example 25-07-2005 into "date"?
    this is how my output statement look like
    myOutput1.print(matcher1.group(1));
    matcher1.group is the way i use to get the value using regular expression

    thanx...actually i have already match it in groups and it works fine..the problem is im dealing with log files...what im trying to do is reformat back the log files collected...example.."8 Nov" change it to 8-11-2005
    When i match it into the group its actually just finding the pattern, not saving it into variable..if its save in the variable would be easier..
    how can i change "8 Nov" to 8-11-2005?? can anyone help me with a simple code???
    thanks

  • Regular Expression Required for Checksum variable

    I am wanting to create a regular expression that extracts a variable checksum value (cs=) which is unique to a given server response string.
    The issue I am having is that a simple regex being name="cs" value="(.+?)" just does not work because there are 18 different checksum values being returned per session id/server response.
    So a simple regex just picks up any "cs" value and I guess gets confused since there are 18 different ones contained within the server response (all user related)
    What i need is a regex to use say this value from the server response (JONHONEYMAN%40YAHOO.COM) or any other unique value which is contained within the string response from the server then extract the cs (Checksum) value from that string and make it variable :)
    Here is the server response string:-
    "fp=220:1200:2977638312763704:: NO::P1200_EMAIL_ADDRESS,P1200_ORGANISATION_NAME,P1200_UCRN,P1200_ORG_ID,P1200_CALLING_PAGE:JONHONEYMAN%40YAHOO.COM%2C john%20Honeyman%2C260%2C220%2C1190&cs=336788D01EC6E80B1877B3EE982E8B2D8" >Select</td></tr
    can anyone help?
    Thanks

    You need an XML Parser.

  • How to add regular expression in viewobject bind variables

    Hi,
    Am using java class to set the adf bind variables
    vm.setWhereClause("FIRST_NAME = :fname");
    vm.defineNamedWhereClauseParam("fname", null, null);
    vm.setNamedWhereClauseParam("fname","Alana");
    It works fine and it returns Alana
    But what i want is to set a regular expression where it returns all the names that are starting with A.
    I tried with this.
    vm.setNamedWhereClauseParam("fname","A*");
    also
    vm.setNamedWhereClauseParam("fname","A%");
    but both didn work.
    Please help.
    Thanks,
    Hari

    Perfect... Thanks Arun.
    I tried including last name too. i.e when either of the one matches (first name or last name)
    vm.setWhereClause("upper(FIRST_NAME) LIKE upper(:fname||'%')");
    vm.defineNamedWhereClauseParam("fname", null, null);
    vm.setNamedWhereClauseParam("fname","A");
    vm.setWhereClause("upper(LAST_NAME) LIKE upper(:lname||'%')");
    vm.defineNamedWhereClauseParam("lname", null, null);
    vm.setNamedWhereClauseParam("lname","A");
    But i guess we should not give it like this as it doesnt seem to work.
    Hari

  • [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?

  • Help regarding regular expression

    HI All ,
    Please see the following string
    String s = "IF ((NOT NUM4 IS ALPHABETIC ) AND NUM3 IS ALPHABETIC-UPPER AND (NUM5 IS GREATER OR EQUAL TO 3) AND (NUM5 IS NOT GREATER THAN 3) AND (NUM3 GREATER THAN 46) AND (NUM5 GREATER THAN NUM3) OR NUM3 LESS THAN 78) .";
    My problem is: i want to capture the part of this line which contains "ALPHABETIC ,ALPHABETIC-UPPER for ex :NOT NUM4 IS ALPHABETIC , NUM3 IS ALPHABETIC-UPPER.from that I have to capture the word num4 , num3 which are in these phrases only ;from the whole string whereever it exists along with the phrase,Can any one help me out by suggesting something.num4 and num3 are variable names

    I suspect you're right, Sabre, but I can't resist...
    import java.util.regex.*;
    * A rewriter does a global substitution in the strings passed to its
    * 'rewrite' method. It uses the pattern supplied to its constructor, and is
    * like 'String.replaceAll' except for the fact that its replacement strings
    * are generated by invoking a method you write, rather than from another
    * string. This class is supposed to be equivalent to Ruby's 'gsub' when given
    * a block. This is the nicest syntax I've managed to come up with in Java so
    * far. It's not too bad, and might actually be preferable if you want to do
    * the same rewriting to a number of strings in the same method or class. See
    * the example 'main' for a sample of how to use this class.
    * @author Elliott Hughes
    public abstract class Rewriter
      private Pattern pattern;
      private Matcher matcher;
       * Constructs a rewriter using the given regular expression; the syntax is
       * the same as for 'Pattern.compile'.
      public Rewriter(String regularExpression)
        this.pattern = Pattern.compile(regularExpression);
       * Returns the input subsequence captured by the given group during the
       * previous match operation.
      public String group(int i)
        return matcher.group(i);
       * Overridden to compute a replacement for each match. Use the method
       * 'group' to access the captured groups.
      public abstract String replacement();
       * Returns the result of rewriting 'original' by invoking the method
       * 'replacement' for each match of the regular expression supplied to the
       * constructor.
      public String rewrite(CharSequence original)
        this.matcher = pattern.matcher(original);
        StringBuffer result = new StringBuffer(original.length());
        while (matcher.find())
          matcher.appendReplacement(result, "");
          result.append(replacement());
        matcher.appendTail(result);
        return result.toString();
      public static void main(String[] args)
        String s = "IF ((NOT NUM4 IS ALPHABETIC ) " +
                    "AND NUM3 IS ALPHABETIC-UPPER " +
                    "AND (NUM5 IS GREATER  OR EQUAL TO 3) " +
                    "AND (NUM5 IS NOT GREATER THAN 3) " +
                    "AND (NUM3 GREATER THAN 46) " +
                    "AND NUM645 IS ALPHABETIC " +
                    "AND (NUM5 GREATER THAN NUM3) " +
                    "OR NUM3 LESS THAN 78 " +
                    "AND NUM34 IS ALPHABETIC-UPPER " +
                    "AND NUM92 IS ALPHABETIC-LOWER " +
                    "AND NUM0987 IS ALPHABETIC-LOWER) .";
        String result =
          new Rewriter("(NUM\\d+) +IS +(ALPHABETIC(?:-(?:UPPER|LOWER))?)")
            public String replacement()
              String type = group(2);
              if (type.endsWith("UPPER"))
                return "Character.isUpper(" + group(1) + ")";
              else if (type.endsWith("LOWER"))
                return "Character.isLower(" + group(1) + ")";
              else
                return "Character.isLetter(" + group(1) + ")";
          }.rewrite(s);
        System.out.println(result);
    }

  • Help with regular expression to find a pattern in clob

    can someone help me writing a regular expression to query a clob that containts xml type data?
    query to find multiple occurrences of a variable string (i.e <EMPID-XX> - XX can be any number). If <EMPID-01> appears twice in the clob i want the result as EMPID-01,2 and if EMPID-02 appears 4 times i want the result as EMPID-02,4.

    with
    ofx_clob as
    (select q'~
    <EMPID>1
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>2
    < UNQID>123457
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>1
    < UNQID>123458
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    ~' ofx from dual
    select '<EMPID>' || to_char(ids) || '(' || to_char(count(*)) || ')' multi_empid
      from (select replace(regexp_substr(ofx,'<EMPID>\d*',1,level),'<EMPID>') ids
              from ofx_clob
            connect by level <= regexp_count(ofx,'<EMPID>')
    group by ids having count(*) > 1
    MULTI_EMPID
    <EMPID>1(2)
    with
    ofx_clob as
    (select q'~
    <EMPID>1
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>2
    < UNQID>123457
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>1
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>2
    < UNQID>123456
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    <EMPID>1
    < UNQID>123458
    < TIMESTAMP>...
    < ADDRINFO>
    < TITLE>^@~*
    < FIRST>ABCD
    < MI>
    < LAST>EFGH
    < ADDR1>ADDR1
    < ADDR2>^@~*
    < CITY>CITY
    ~' ofx from dual
    select '<EMPID>' || listagg(to_char(ids) || '(' || to_char(count(*)) || ')',',') within group (order by ids) multi_empid
      from (select replace(regexp_substr(ofx,'<EMPID>\d*',1,level),'<EMPID>') ids
              from ofx_clob
            connect by level <= regexp_count(ofx,'<EMPID>')
    group by ids having count(*) > 1
    MULTI_EMPID
    <EMPID>1(3),2(2)
    Regards
    Etbin
    Message was edited by: Etbin
    used listagg to report more than one multiple <EMPID>

  • [SOLVED]ZSH and regular expressions

    Hi
    I am getting into regular expressions and i have noticed that with my .zshrc file i have some problem. In bash this expression works:
    \^\[^#]
    but not also in zsh. I have also noted that regular expression works fine with other zshrc configurations found in archwiki (like grml) but i want to have my configuration. And i really can't find what command make a difference
    My .zshrc file is pulled from this site https://github.com/slashbeast/things/bl … s/DOTzshrc.
    # .zshrc
    # Author: Piotr Karbowski <[email protected]>
    # License: beerware.
    # Basic zsh config.
    umask 077
    ZDOTDIR=${ZDOTDIR:-${HOME}}
    ZSHDDIR="${HOME}/.config/zsh.d"
    HISTFILE="${ZDOTDIR}/.zsh_history"
    HISTSIZE='10000'
    SAVEHIST="${HISTSIZE}"
    export EDITOR="/usr/bin/vim"
    export TMP="$HOME/tmp"
    export TEMP="$TMP"
    export TMPDIR="$TMP"
    export TMPPREFIX="${TMPDIR}/zsh"
    if [ ! -d "${TMP}" ]; then mkdir "${TMP}"; fi
    if ! [[ "${PATH}" =~ "^${HOME}/bin" ]]; then
    export PATH="${HOME}/bin:${PATH}"
    fi
    # Not all servers have terminfo for rxvt-256color. :<
    if [ "${TERM}" = 'rxvt-256color' ] && ! [ -f '/usr/share/terminfo/r/rxvt-256color' ] && ! [ -f '/lib/terminfo/r/rxvt-256color' ] && ! [ -f "${HOME}/.terminfo/r/rxvt-256color" ]; then
    export TERM='rxvt-unicode'
    fi
    # Colors.
    red='\e[0;31m'
    RED='\e[1;31m'
    green='\e[0;32m'
    GREEN='\e[1;32m'
    yellow='\e[0;33m'
    YELLOW='\e[1;33m'
    blue='\e[0;34m'
    BLUE='\e[1;34m'
    purple='\e[0;35m'
    PURPLE='\e[1;35m'
    cyan='\e[0;36m'
    CYAN='\e[1;36m'
    NC='\e[0m'
    # Functions
    if [ -f '/etc/profile.d/prll.sh' ]; then
    . "/etc/profile.d/prll.sh"
    fi
    run_under_tmux() {
    # Run $1 under session or attach if such session already exist.
    # $2 is optional path, if no specified, will use $1 from $PATH.
    # If you need to pass extra variables, use $2 for it as in example below..
    # Example usage:
    # torrent() { run_under_tmux 'rtorrent' '/usr/local/rtorrent-git/bin/rtorrent'; }
    # mutt() { run_under_tmux 'mutt'; }
    # irc() { run_under_tmux 'irssi' "TERM='screen' command irssi"; }
    # There is a bug in linux's libevent...
    # export EVENT_NOEPOLL=1
    command -v tmux >/dev/null 2>&1 || return 1
    if [ -z "$1" ]; then return 1; fi
    local name="$1"
    if [ -n "$2" ]; then
    local file_path="$2"
    else
    local file_path="command ${name}"
    fi
    if tmux has-session -t "${name}" 2>/dev/null; then
    tmux attach -d -t "${name}"
    else
    tmux new-session -s "${name}" "${file_path}" \; set-option status \; set set-titles-string "${name} (tmux@${HOST})"
    fi
    t() { run_under_tmux rtorrent; }
    irc() { run_under_tmux irssi "TERM='screen' command irssi"; }
    over_ssh() {
    if [ -n "${SSH_CLIENT}" ]; then
    return 0
    else
    return 1
    fi
    reload () {
    exec "${SHELL}" "$@"
    confirm() {
    local answer
    echo -ne "zsh: sure you want to run '${YELLOW}$@${NC}' [yN]? "
    read -q answer
    echo
    if [[ "${answer}" =~ ^[Yy]$ ]]; then
    command "${=1}" "${=@:2}"
    else
    return 1
    fi
    confirm_wrapper() {
    if [ "$1" = '--root' ]; then
    local as_root='true'
    shift
    fi
    local runcommand="$1"; shift
    if [ "${as_root}" = 'true' ] && [ "${USER}" != 'root' ]; then
    runcommand="sudo ${runcommand}"
    fi
    confirm "${runcommand}" "$@"
    poweroff() { confirm_wrapper --root $0 "$@"; }
    reboot() { confirm_wrapper --root $0 "$@"; }
    hibernate() { confirm_wrapper --root $0 "$@"; }
    detox() {
    if [ "$#" -ge 1 ]; then
    confirm detox "$@"
    else
    command detox "$@"
    fi
    has() {
    local string="${1}"
    shift
    local element=''
    for element in "$@"; do
    if [ "${string}" = "${element}" ]; then
    return 0
    fi
    done
    return 1
    begin_with() {
    local string="${1}"
    shift
    local element=''
    for element in "$@"; do
    if [[ "${string}" =~ "^${element}" ]]; then
    return 0
    fi
    done
    return 1
    termtitle() {
    case "$TERM" in
    rxvt*|xterm|nxterm|gnome|screen|screen-*)
    local prompt_host="${(%):-%m}"
    local prompt_user="${(%):-%n}"
    local prompt_char="${(%):-%~}"
    case "$1" in
    precmd)
    printf '\e]0;%s@%s: %s\a' "${prompt_user}" "${prompt_host}" "${prompt_char}"
    preexec)
    printf '\e]0;%s [%s@%s: %s]\a' "$2" "${prompt_user}" "${prompt_host}" "${prompt_char}"
    esac
    esac
    git_check_if_worktree() {
    # This function intend to be only executed in chpwd().
    # Check if the current path is in git repo.
    # We would want stop this function, on some big git repos it can take some time to cd into.
    if [ -n "${skip_zsh_git}" ]; then
    git_pwd_is_worktree='false'
    return 1
    fi
    # The : separated list of paths where we will run check for git repo.
    # If not set, then we will do it only for /root and /home.
    if [ "${UID}" = '0' ]; then
    # running 'git' in repo changes owner of git's index files to root, skip prompt git magic if CWD=/home/*
    git_check_if_workdir_path="${git_check_if_workdir_path:-/root:/etc}"
    else
    git_check_if_workdir_path="${git_check_if_workdir_path:-/home}"
    git_check_if_workdir_path_exclude="${git_check_if_workdir_path_exclude:-${HOME}/_sshfs}"
    fi
    if begin_with "${PWD}" ${=git_check_if_workdir_path//:/ }; then
    if ! begin_with "${PWD}" ${=git_check_if_workdir_path_exclude//:/ }; then
    local git_pwd_is_worktree_match='true'
    else
    local git_pwd_is_worktree_match='false'
    fi
    fi
    if ! [ "${git_pwd_is_worktree_match}" = 'true' ]; then
    git_pwd_is_worktree='false'
    return 1
    fi
    # todo: Prevent checking for /.git or /home/.git, if PWD=/home or PWD=/ maybe...
    # damn annoying RBAC messages about Access denied there.
    if [ -d '.git' ] || [ "$(git rev-parse --is-inside-work-tree 2> /dev/null)" = 'true' ]; then
    git_pwd_is_worktree='true'
    git_worktree_is_bare="$(git config core.bare)"
    else
    unset git_branch git_worktree_is_bare
    git_pwd_is_worktree='false'
    fi
    git_branch() {
    git_branch="$(git symbolic-ref HEAD 2>/dev/null)"
    git_branch="${git_branch##*/}"
    git_branch="${git_branch:-no branch}"
    git_dirty() {
    if [ "${git_worktree_is_bare}" = 'false' ] && [ -n "$(git status --untracked-files='no' --porcelain)" ]; then
    git_dirty='%F{green}*'
    else
    unset git_dirty
    fi
    precmd() {
    # Set terminal title.
    termtitle precmd
    if [ "${git_pwd_is_worktree}" = 'true' ]; then
    git_branch
    git_dirty
    git_prompt=" %F{blue}[%F{253}${git_branch}${git_dirty}%F{blue}]"
    else
    unset git_prompt
    fi
    preexec() {
    # Set terminal title along with current executed command pass as second argument
    termtitle preexec "${(V)1}"
    chpwd() {
    git_check_if_worktree
    man() {
    if command -v vimmanpager >/dev/null 2>&1; then
    PAGER="vimmanpager" command man "$@"
    else
    command man "$@"
    fi
    # Are we running under grsecurity's RBAC?
    rbac_auth() {
    local auth_to_role='admin'
    if [ "${USER}" = 'root' ]; then
    if ! grep -qE '^RBAC:' "/proc/self/status" && command -v gradm > /dev/null 2>&1; then
    echo -e "\n${BLUE}*${NC} ${GREEN}RBAC${NC} Authorize to '${auth_to_role}' RBAC role."
    gradm -a "${auth_to_role}"
    fi
    fi
    #rbac_auth
    # Check if we started zsh in git worktree, useful with tmux when your new zsh may spawn in source dir.
    git_check_if_worktree
    if [ "${git_pwd_is_worktree}" = 'true' ]; then
    git_branch
    git_dirty
    git_prompt=" %F{blue}[%F{253}${git_branch}${git_dirty}%F{blue}]"
    else
    unset git_prompt
    fi
    # Le features!
    # extended globbing, awesome!
    setopt extendedGlob
    # zmv - a command for renaming files by means of shell patterns.
    autoload -U zmv
    # zargs, as an alternative to find -exec and xargs.
    autoload -U zargs
    # Turn on command substitution in the prompt (and parameter expansion and arithmetic expansion).
    setopt promptsubst
    # Control-x-e to open current line in $EDITOR, awesome when writting functions or editing multiline commands.
    autoload -U edit-command-line
    zle -N edit-command-line
    bindkey '^x^e' edit-command-line
    # Include user-specified configs.
    if [ ! -d "${ZSHDDIR}" ]; then
    mkdir -p "${ZSHDDIR}" && echo "# Put your user-specified config here." > "${ZSHDDIR}/example.zsh"
    fi
    for zshd in $(ls -A ${HOME}/.config/zsh.d/^*.(z)sh$); do
    . "${zshd}"
    done
    # Completion.
    autoload -Uz compinit
    compinit
    zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
    zstyle ':completion:*' completer _expand _complete _ignored _approximate
    zstyle ':completion:*' menu select=2
    zstyle ':completion:*' select-prompt '%SScrolling active: current selection at %p%s'
    zstyle ':completion::complete:*' use-cache 1
    zstyle ':completion:*:descriptions' format '%U%F{cyan}%d%f%u'
    # If running as root and nice >0, renice to 0.
    if [ "$USER" = 'root' ] && [ "$(cut -d ' ' -f 19 /proc/$$/stat)" -gt 0 ]; then
    renice -n 0 -p "$$" && echo "# Adjusted nice level for current shell to 0."
    fi
    # Fancy prompt.
    if over_ssh && [ -z "${TMUX}" ]; then
    prompt_is_ssh='%F{blue}[%F{red}SSH%F{blue}] '
    elif over_ssh; then
    prompt_is_ssh='%F{blue}[%F{253}SSH%F{blue}] '
    else
    unset prompt_is_ssh
    fi
    case $USER in
    root)
    PROMPT='%B%F{cyan}%m%k %(?..%F{blue}[%F{253}%?%F{blue}] )${prompt_is_ssh}%B%F{blue}%1~${git_prompt}%F{blue} %# %b%f%k'
    PROMPT='%B%F{blue}%n@%m%k %(?..%F{blue}[%F{253}%?%F{blue}] )${prompt_is_ssh}%B%F{cyan}%1~${git_prompt}%F{cyan} %# %b%f%k'
    esac
    # Ignore lines prefixed with '#'.
    setopt interactivecomments
    # Ignore duplicate in history.
    setopt hist_ignore_dups
    # Prevent record in history entry if preceding them with at least one space
    setopt hist_ignore_space
    # Nobody need flow control anymore. Troublesome feature.
    #stty -ixon
    setopt noflowcontrol
    # Fix for tmux on linux.
    case "$(uname -o)" in
    'GNU/Linux')
    export EVENT_NOEPOLL=1
    esac
    # Aliases
    alias cp='cp -iv'
    alias rcp='rsync -v --progress'
    alias rmv='rsync -v --progress --remove-source-files'
    alias mv='mv -iv'
    alias rm='rm -iv'
    alias rmdir='rmdir -v'
    alias ln='ln -v'
    alias chmod="chmod -c"
    alias chown="chown -c"
    if command -v colordiff > /dev/null 2>&1; then
    alias diff="colordiff -Nuar"
    else
    alias diff="diff -Nuar"
    fi
    alias grep='grep --colour=auto'
    alias egrep='egrep --colour=auto'
    alias ls='ls --color=auto --human-readable --group-directories-first --classify'
    # Keys.
    case $TERM in
    rxvt*|xterm*)
    bindkey "^[[7~" beginning-of-line #Home key
    bindkey "^[[8~" end-of-line #End key
    bindkey "^[[3~" delete-char #Del key
    bindkey "^[[A" history-beginning-search-backward #Up Arrow
    bindkey "^[[B" history-beginning-search-forward #Down Arrow
    bindkey "^[Oc" forward-word # control + right arrow
    bindkey "^[Od" backward-word # control + left arrow
    bindkey "^H" backward-kill-word # control + backspace
    bindkey "^[[3^" kill-word # control + delete
    linux)
    bindkey "^[[1~" beginning-of-line #Home key
    bindkey "^[[4~" end-of-line #End key
    bindkey "^[[3~" delete-char #Del key
    bindkey "^[[A" history-beginning-search-backward
    bindkey "^[[B" history-beginning-search-forward
    screen|screen-*)
    bindkey "^[[1~" beginning-of-line #Home key
    bindkey "^[[4~" end-of-line #End key
    bindkey "^[[3~" delete-char #Del key
    bindkey "^[[A" history-beginning-search-backward #Up Arrow
    bindkey "^[[B" history-beginning-search-forward #Down Arrow
    bindkey "^[Oc" forward-word # control + right arrow
    bindkey "^[Od" backward-word # control + left arrow
    bindkey "^H" backward-kill-word # control + backspace
    bindkey "^[[3^" kill-word # control + delete
    esac
    bindkey "^R" history-incremental-pattern-search-backward
    bindkey "^S" history-incremental-pattern-search-forward
    if [ -f ~/.alert ]; then cat ~/.alert; fi
    Thanks for all the help.
    Last edited by Shark (2013-05-11 22:32:24)

    Raynman wrote:
    "This expression doesn't work", "It doesn't work" ...
    Could you try being a bit more specific?
    Firstly, i am sorry i didn't post the output. I should have know better.
    Secondly, chill out.
    I have used above regex with grep command. Output from terminal is:
    zsh: bad pattern: ^[^#]
    In bash it works perfectly.
    If i issue "setopt re_match_pcre" i have the same ouput as above.
    EDIT: If i issue "unsetopt no_match" it actually works but i have to change the regex from "\^\[^#]" to "\^[^#]" otherwise i get the same output as above. In bash both options work.
    Last edited by Shark (2013-05-11 22:07:21)

  • Use regular expressions to extract .llb filename from path

    I am trying to be clever (always a dangerous thing) and use a regular expression to extract the name of a library from a filepath converted to a string.   Whilst I appreciate there are other ways to do this, regex would appear to be a very powerful neat way, should I be able to get it to work.
    i.e if I have a string of the type, C:\applications\versions\library.llb\toplevel.vi, I want to be able to extract library.llb from the string, given that it will be of variable length, may include numbers & spaces and may be within a file hierarchy of variable depth.   In other words, I want to extract the portion of the string between the last \ that ends with .llb
    The best I have managed so far, is \\+.*llb which returned everything minus the drive letter and the toplevel.vi
    Can anyone help me achieve this, or am i better using an alternative method (e.g filepath to array string, search for .llb)
    Thanks
    Matt
    Solved!
    Go to Solution.

    Hi Matt,
    attached you'll find two other options.
    Mike
    Message Edited by MikeS81 on 04-13-2010 01:30 PM
    Attachments:
    Path.PNG ‏7 KB

  • Java Regular Expressions and Pattern

    I have a file that i first want to get all the lines that match a given pattern. Then from these lines that match i want to extract two values.
    Example line for the pattern to match
    INFO | jvm 1 | 2006/11/07 15:14:09 | INFO | Tue Nov 07 15:14:09 CET 2006 | XLDB PPS Data Dumper: MESSAGE:- 406 Processing .. '[ /opt/nexus/horizon/raw_data/network/pp_CE01S4H_sta_20050703T015717_SYDP3001_546.bdf ]'
    So all the lines that are like these i want to extract two variables
    2006/11/07 15:14:09
    and
    /opt/nexus/horizon/raw_data/network/pp_CE01S4H_sta_20050703T015717_SYDP3001_546.bdf
    so i can store these variables in a database.
    Can someone help me with writing the pattern to match and the regular express to extract? Also if anyone else has a better way of doing this i am all ears and i have a lot of log files to go through.

    import java.util.regex.*;
    class Main
      public static void main(String[] args)
        String txt="INFO | jvm 1 | 2006/11/07 15:14:09 | INFO | Tue Nov 07 15:14:09 CET 2006 | XLDB PPS Data Dumper: MESSAGE:- 406 Processing .. '[ /opt/nexus/horizon/raw_data/network/pp_CE01S4H_sta_20050703T015717_SYDP3001_546.bdf ]'";
        String re1=".*?";     // Non-greedy match on filler
        String re2="((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))";     // Time Stamp 1
        String re3=".*?";     // Non-greedy match on filler
        String re4="((?:\\/[\\w\\.]+)+)";     // Unix Path 1
        Pattern p = Pattern.compile(re1+re2+re3+re4,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(txt);
        if (m.find())
            String timestamp1=m.group(1);
            String unixpath1=m.group(2);
            System.out.print("("+timestamp1.toString()+")"+"("+unixpath1.toString()+")"+"\n");
    }

  • Need help in unix regular expressions

    Hi All,
    I'm new to shell scripting. Please help me in achieving this
    I am trying to a find regular expression that need to pick a file with begin with the below format and mask variable is called in xml file.
    currently the script accepts:
    mask="CLIENT_ID+'_ADHSUITE_IN_'+date2str(now,'MMddyy','US/Eastern')+'.txt'"
    But it should accept in the below format
    2595_ADHSUITE_IN_ANNWEL_030309_2009-02-10_15-12-46-000_648.TXT715.outpgp_out
    where CLIENT_ID=2595. How to place wild card character '*' in the below to accept file in the above format. here is what i made changes.
    mask="CLIENT_ID+'_ADHSUITE_IN_'*+date2str(now,'MMddyy','US/Eastern')*+'.TXT'*+'.outpgp_out'"
    Please help.
    Thanks

    I believe your statement is being passed over twice:
    First Pass: (This is done by something like javascript)
    CLIENT_ID+'_ADHSUITE_IN_'+'.*'+date2str(now,'MMddyy','US/Eastern')+'.*'+'.TXT'+'.*'+'.outpgp_out'In this pass the variables and functions that are enclosed in literals are processed:
    (1) CLIENT_ID is replaced by 2595 or whatever is current value is:
    (2) date2str(now,'MMddyy','US/Eastern') gets replaced by 040609 (if the current time now is 4th april 2009).
    So at the end of this first pass we have a string:
    2595_ADHSUITE_IN_.\*040609.\*.TXT.*.outpgp_outThis string at the end of the first pass is a Posix basic regular expression. (ref: [http://en.wikipedia.org/wiki/Regular_expression] ) accessed at time of post).
    This is the string I put in the Regular Expression text box on [http://www.fileformat.info/tool/regex.htm]
    and it matches "2595_ADHSUITE_IN_ANNWEL_040609_2009-01-27_17-02-28-000_631.TXT715.outpgp_out" for me (though I prefer my egrep test).
    I hope this is somewhat clearer. Remember I have very little information about your system/application and I make big guesses.
    NB: (I should thank Frits earlier for pointing my sloppiness between wildcards (for eg unix shell filename expansion) and regular expressions).
    For the second pass this used to compared other strings to see

  • 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.

  • Help needed regarding regular expressions

    hello
    i need to write a program that recieves a matematical expression and evaluates
    it...in other words a calculator :)
    i know i need to use regular expressions inorder to determine if the input is legal or not ,but i'm really having trouble setting the pattern
    the expression can be in the form : Axxze2223+log(5)+(2*3)*(5+4)
    where Axxze2223 is a variable(i.e a combination of letters and numbers.)
    where as: l o g (5) or log() or Axxx33aaaa or () are illegal
    i tried to set the pattern but i got exceptions or it just didnt work the way i wanted it .
    here's what i tried to do at least for the varibale form:
    "\\s*(*([a-zA-Z]+\\d)+)*\\s*";
    i'm really new to this...and i can't seem to set the pattern by using regular expressions,how can i combine all the rules to one string?
    any help or references would be appreciated
    thanks

    so i'll explain
    let's say i got token "abc22c"(let's call it "token")
    i wan't to check if it's legal
    i define:
    String varPattern = "\\s*[a-zA-Z]+\\d+\\s*";If you want to check a sequence of ASCII characters, longer than one, followed by a single digit, the whole possibly surrounded by spaces -- yes.
    >
    now i want to check if it's o.k
    so i check:
    token.matches(varPattern);
    am i correct?Quite. It's better to compile the Pattern (Pattern.compile(String)), create a java.util.regex.Matcher (Pattern#matcher(CharSequence)), and test the Matcher for Matcher#matches().
    (Class.method -> static method, Class#method -> instance method)
    >
    now i'm having problem defining pattern for log()
    sin() cos()
    that brackets are mandatory ,and there must be an
    expression inside
    how do i do that?First, I'd check the overall function syntax (a valid name, brackets), then whether what's inside the brackets is a valid expression (maybe empty), then whether that expression is valid for that function (presumably always?).
    I might add I'm no expert on parsing, so that's more a supposition than a guide.

Maybe you are looking for