aneuryzm
aneuryzm

Reputation: 64854

Regular Expressions: how to accept any symbol

I want to replace any content in my text file in between symbols < and >

What's the regular expression to accept any symbol ? I've currently:

fields[i] = fields[i].replaceAll("\\<[a-z0-9_-]*\\>", "");

But it works only for letters and numbers, if there is a symbol in between < and >, the string is not replaced.

thanks

Upvotes: 30

Views: 169268

Answers (4)

Intrepidd
Intrepidd

Reputation: 20908

To accept any symbol, .* should do the trick.

E.g.: fields[i] = fields[i].replaceAll("\\<.*\\>", "");

Upvotes: 60

Anthony Nandaa
Anthony Nandaa

Reputation: 3400

This is generic for the bigger-picture approach, say you wanted to clean out (or select) any symbols from a string.

A cleaner approach will be to select anything that is not alphanumeric, which by elimination must be a symbol, simply by using /\W/, see [1]. The regex will be

let re = /\W/g

// for example, given a string and you would like to
// clean out any non-alphanumerics
// remember this will include the spaces

let s = "he$$llo# worl??d!"

s = s.replace(re, '') // "helloworld"

However, if you need to exclude all non-alphanumerics except a few, say "space" from our previous example. You can use the [^ ...] (hat) pattern.

let re = /[^ \w]/g    // match everything else except space and \w (alphanumeric)

let s = "he$$llo# worl??d!"

s = s.replace(re, '')  // "hello world"

References:

[1] https://regexone.com/

Upvotes: 4

Madars Vi
Madars Vi

Reputation: 1017

Any char in regexp is "." the "*" - is quantifier, how many. Thus if you want just one char, then use "." (dot) and that's it.

Upvotes: 5

xanatos
xanatos

Reputation: 111920

Try this [^\>]* (any character that isn't >)

Upvotes: 26

Related Questions