Home > Blockchain >  Match the first string that starts with // up to the first space with regex
Match the first string that starts with // up to the first space with regex

Time:10-01

I'm trying to extract the first string starting with // to the first space. So far I have ^(\A\w ) but it only gives me the first word and I cant figure out how to tell it to also match starting with //

For example:

#Sample text
//AnyNumberORLetter notthis <-- only want to match //AnyNumberORLetter  
//HELLO WORLD

Edit typo

Edit 2: sorry I am using Ansible with regex

    - name: "replace job name"
      ansible.builtin.lineinfile:
        path: "{{jcl_path}}"
        regexp: '^(\A\w )'
        line: '{{job_name}}'
        group: dart
        mode: g rw
      delegate_to: localhost

CodePudding user response:

To also start with // you can make the // optional:

^(?://)?\w 

Regex demo

To only start with //

^//\w 

Regex demo

CodePudding user response:

This captures your target as group 1:

(//\S )([\s\S]*)

and remove line: and add replace: '\1 {{job_name}}'\2

See live demo.

regex breakdown:

  • ^ means start
  • \S means a non-whitespace character
  • means one or more of the preceding expression
  • [\s\S]* means the rest of the input (works with any flavour of regex)
  • Related