1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Regex woes! Help needed.

Discussion in 'HTML, Graphics & Programming' started by Punt, Apr 18, 2018.

  1. Punt

    Wise Guy

    Joined: Nov 17, 2003

    Posts: 1,405

    Location: Gateshead

    Why? I don't know, but I've never been able to wrap my head around regular expressions. Now I'm stuck, not even sure it's possible, but it probably is :)

    I need to test a string for 'test'. Simple enough. This 'test' must also be at the start of the string. Still simple enough. 'test' at the start of the string must NOT be followed by ' -' (space hyphen), this is where I'm stuck.

    eg...

    test blahblahblah - pass
    test - blahblahblah - fail, followed by ' -'
    a test blahblahblah - fail, not start of string.
    a test - blahblahblah - fail, not start of string and followed by ' -'

    Note: blahblahblah will be a random number and selection of characters but 'test' will always be 'test'.

    Ultimately, I need to rename millions of files of the format 'test blahblahblah' to 'test - blahblahblah' without renaming them 'test - - blahblahblah'. Hope that make sense??

    Anyone good with regex help me out?

    Cheers !
     
  2. touch

    Capodecina

    Joined: Oct 28, 2006

    Posts: 10,530

    Location: Sufferlandria

    If it's always followed by a number, it would be easier to just match that rather than trying to not match the dash.

    something like:
    "^test[0-9]"
    ^ matches from the start of the string
    test matches the word test
    [0-9] matches any digit

    Use this site to build and test it https://regex101.com/
     
  3. Punt

    Wise Guy

    Joined: Nov 17, 2003

    Posts: 1,405

    Location: Gateshead

    Sorry, when I said 'a random number and selection of characters' I perhaps wasn't clear, it'll be a mix of digits and characters.

    You have got me thinking though as blahblahblah will always be alphanumeric.

    Hmmm???
     
  4. Poolybit

    Hitman

    Joined: May 14, 2006

    Posts: 943

    Something like this?

    (^test)(?!([\ ][\-]))
     
  5. Punt

    Wise Guy

    Joined: Nov 17, 2003

    Posts: 1,405

    Location: Gateshead

    Cheers Guys, Sorted :)

    touch pointed me in the right direction. Poolybit's solution also works.
     
  6. amigafan2003

    Capodecina

    Joined: Jan 18, 2008

    Posts: 13,714

    Location: Fylde Coast, Lancashire

    A developer had one problem he decided to solve by using a regular expression.

    Now he has two problems.
     
  7. Punt

    Wise Guy

    Joined: Nov 17, 2003

    Posts: 1,405

    Location: Gateshead

    I believe that!!

    It is very powerful once I understand and I'm finally getting my head around it. I really should have learned this years ago, it's just so foreign! :)