0

I have a bunch of HTML files I need to search to find where a class name is used in the application.

Ex1: should match both of these:

<div class="something else field">Foo</div>
<span class="field">Bar</span>

Ex2: should not match

<div class="baseball-field baz">Baz</div>

I need a pattern to find a class name in my files

What I've tried is: /class(?=field)/

But this doesn't work, I'm not sure how to account for possible other characters in the search.

Update:

I tried: class.*(?=field), that works for Ex1 but not 2

SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98

2 Answers2

1

Your regex is almost correct but you want to search for class="field" while your regex just check for classfield.

So, you can use this regex instead:

class(?=="field")

Regex demo

In addition, not sure what tool/language you are using, but consider using an html parser instead or xpath/xquery instead.

Update: since you updated your question, here I provided the updates for the answer. You could use this regex instead:

class(?=="(?:field|.*?\sfield|field\s.*?)")

Working demo

Btw, if you want to merge above alternations you could use:

class(?=="(?:(?:.*?\s)?field(?:\s.*?)?)")

You could clean up a bit the regex above removing the non-capturing groups to

class(?=="((.*?\s)?field(\s.*?)?)")
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
0

The accepted answer is close, but is missing one fourth important case:

  1. class="field"
  2. class="foo field"
  3. class="field bar"
  4. class="foo field bar"

Here is the RegExp that is true for each of the above cases, but false if anything other than a space or quotation mark is next to the 'field' class:

class(?=="(?:field|.*?\sfield|field\s.*?|.*?\sfield\s.*?)")

See an updated Demo.