Tai
Tai

Reputation: 1256

Searching XCode for strings starting with _

I read: Regular Expression to match string starting with "stop"

I want to search for all strings starting with a _ character using regex search in XCode (in case that matters) which I initially thought I would be able to search for with ^_ but that only returns me lines that start with _ they exclude lines with spaces.

I would like my search to return all of the following:

_foo
 _bar
  _baz

for example and exclude things like

foo_bar 
#_
  wholeWord_anotherWord

or any other string that doesnt start with '_' followed by myString (ex _myString is a desired result). Basically I'm looking for all variables following the _ naming convention.

I read: How to ignore whitespace in a regular expression subject string?

I tried "\s*^_" but that returned me only 'new line'_aString. Did I misunderstand the solution? What will give me the correct response of any _variable?

Upvotes: 0

Views: 777

Answers (1)

hmedia1
hmedia1

Reputation: 6180

I initially thought I would be able to search for with ^_ but that only returns me lines that start with _ they exclude lines with spaces

Given that:

  • You say ^_ works for the lines that don't start with spaces; and
  • You wish you exclude lines such as foo_bar, (or " foo_bar" for that matter)
  • You are using the Xcode regex search box

Then I have found any of the following combinations:

  • ^\s*_
  • ^\s+?_
  • ^[:space:]*_

Will return matches for each of the following:

_foo
 _bar
  _baz

Note that the [:space:] character class accounts for all whitespace (tabs, form feeds, carriage return, etc).

You can return the entire string that starts with any of these criteria by adding (.*$) to the above regex' respectively;

  • (^\s*_\w+)(\s*)(.*$)
  • (^\s+?_\w+)(\s*)(.*$)
  • (^[:space:]*_\w+)([:space:]*)(.*$)

If separation is required then the back reference \1 would be _var and back reference \3 would be the string after the _var if separated by a whitespace.

Upvotes: 1

Related Questions