Replace all characters that aren’t letters and numbers with a hyphen [duplicate]

This should do what you’re looking for: function clean($string) { $string = str_replace(‘ ‘, ‘-‘, $string); // Replaces all spaces with hyphens. return preg_replace(‘/[^A-Za-z0-9\-]/’, ”, $string); // Removes special chars. } Usage: echo clean(‘a|”bc!@┬úde^&$f g’); Will output: abcdef-g Edit: Hey, just a quick question, how can I prevent multiple hyphens from being next to each … Read more

What to do when a regular expression pattern doesn’t match anywhere in a string?

Oh Yes You Can Use Regexes to Parse HTML! For the task you are attempting, regexes are perfectly fine! It is true that most people underestimate the difficulty of parsing HTML with regular expressions and therefore do so poorly. But this is not some fundamental flaw related to computational theory. That silliness is parroted a … Read more

In regex, what does [\w*] mean?

Quick answer: ^[\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*). Details: The “\w” means “any word character” which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_) The “^” “anchors” to the beginning of a string, and … Read more

regular expressions: match x times OR y times

^(\d{3}|\d{6})$ You have to have some sort of terminator otherwise \d{3} will match 1234. That’s why I put ^ and $ above. One alternative is to use lookarounds: (?<!\d)(\d{3}|\d{6})(?!\d) to make sure it’s not preceded by or followed by a digit (in this case). More in Lookahead and Lookbehind Zero-Width Assertions.

C# Regex.Split: Removing empty results

Regex lineSplitter = new Regex(@”[\s*\*]*\|[\s*\*]*”); var columns = lineSplitter.Split(data).Where(s => s != String.Empty); or you could simply do: string[] columns = data.Split(new char[] {‘|’}, StringSplitOptions.RemoveEmptyEntries); foreach (string c in columns) this.textBox1.Text += “[” + c.Trim(‘ ‘, ‘*’) + “] ” + “\r\n”; And no, there is no option to remove empty entries for RegEx.Split as … Read more

capturing group in regex [duplicate]

The first one won’t store the capturing group, e.g. $1 will be empty. The ?: prefix makes it a non capturing group. This is usually done for better performance and un-cluttering of back references. In the second example, the characters in the capturing group will be stored in the backreference $1. Further Reading.