0

I'm trying to create a regex to match a string, which has a * placeholder. The problem for me is, that this placeholder could optionally have some characters in front:

I came up with /(.*)(\w)\*(.*)/:

This is ju* an example
This is * an example
T* is just an example
* is just an example
This is just an ex*
This is just an *

I need to get three parts of each string:

  1. The first part of the string before the placeholder (with optional prepended string),
  2. the prepended placeholder string itself and
  3. the rest of the string.

So the result should be:

This is|ju|an example
This is|<null>|an example
<null>|T|is just an example
<null>|<null>|is just an example
This is just an|ex|<null>
This is just an|<null>|<null>    

https://regex101.com/r/0pFhdE/1

user3142695
  • 15,844
  • 47
  • 176
  • 332

4 Answers4

1

What I tried is:

^(.*?)[^\S\n]*([^\s*]*)\*[^\S\n]*(.*)$

See an online demo


  • ^ - Start-line anchor;
  • (.*?) - Your 1st capture group with 0+ (Lazy) characters other than newline;
  • [^\S\n]* - 0+ (Greedy) character that are not non-whitespace characters or newline. I guess you may swap to \s* in your application, but for demonstration purposes I used this;
  • ([^\s*]*) - A 2nd capture group to match 0+ (Greedy) characters other than whitespace or asterisks;
  • \*[^\S\n]* - A literal asterisks, followed by 0+ (Greedy) characters that are not non-whitespace or newline;
  • (.*) - A 3rd capture group to catch 0+ (Greedy) characters other than newline;
  • $ - End-line anchor.
JvdV
  • 70,606
  • 8
  • 39
  • 70
0

This seems to match your requirements.

/^(.*?)(\w*)\*(.*)/g

const arr = [
  "This is ju* an example",
  "This is * an example",
  "T* is just an example",
  "* is just an example",
  "This is just an ex*",
  "This is just an *",
];

console.log(
  arr.map(x => {
    const myRegexp = /^(.*?)(\w*)\*(.*)/g; // new RegExp("", "gm");
    const match = myRegexp.exec(x);
    return match.map(x => x.trim());
  })
);
.as-console-wrapper {
  max-height: 100vh !important;
}

Reference: greedy and lazy matching

Naren Murali
  • 19,250
  • 3
  • 27
  • 54
0

Use yourString.split(/(\w**)/)

the responses will be:

[ "This is ", "ju*", " an example" ]

[ "This is ", "*", " an example" ]

[ "", "T*", " is just an example" ]

[ "", "*", " is just an example" ]

[ "This is just an ", "ex*", "" ]

[ "This is just an ", "*", "" ]

handle the blanks and * to match your outcome

Anshuman
  • 831
  • 5
  • 18
0

You could look for

/([ ]*)(\w*)\*(\w*)/gm
  • a space, optional,
  • word characters, optional
  • a star
  • word characters, optional
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392