-1

I am trying to match a string "menu-item" but has a digit after it.

<li id="menu-item-578" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-578">

i can use this regex

menu-item-[0-9]*

however it matches all the menu-item string, i want to only match the "menu-item-578" but not id="menu-item-578"enter image description here

how can i do it?

thank you

revo
  • 47,783
  • 14
  • 74
  • 117
cryptohustla
  • 45
  • 1
  • 7

3 Answers3

1

You should avoid using menu-item-[0-9]* not because it matches the same expected substring superfluously but for the reason that it goes beyond that too like matching menu-item- in menu-item-one.

Besides replacing quantifier with +, you have to look if preceding character is not a non-whitespace character:

(?<!\S)menu-item-[0-9]+(?=["' ])

or if your regex flavor doesn't support lookarounds you may want to do this which may not be precise either:

[ ]menu-item-[0-9]+

You may also consider following characters using a more strict pattern:

[ ]menu-item-[0-9]+["' ]
revo
  • 47,783
  • 14
  • 74
  • 117
0

Use a space before, like this:

\ menu-item-[0-9]*

The first ocurrence has an " right before, while the second one has a space.

EDIT: use an online regex editor (like Regex tester to try this things.

jjimenezg93
  • 162
  • 4
  • 16
  • it highlight all the menu-item aside from the one in id lol can it be more strict to just highlight the one with digit? – cryptohustla Apr 08 '18 at 09:44
0

Try it works too:

(\s)(menu-item-)\d+

https://regex101.com/

  • \s Any whitespace character
revo
  • 47,783
  • 14
  • 74
  • 117
pedram shabani
  • 1,654
  • 2
  • 20
  • 30