Reputation: 275
I'm trying to find the proper regular expression to select a term if it does NOT include hyphens. For example, I want to find the term debt
but not debt-to-income
.
I've got \bdebt-to-income\b
which will select just debt-to-income
, but I need the opposite. Help!
Upvotes: 1
Views: 3427
Reputation: 4075
If the purpose is to find specific words in a stream of characters, where words are defined as a consecutive number of characters including hyphens, then I think \b needs to be abandoned as it in Javascript considers hyphens as word boundaries. Examples would be in-debt or debt-to-income which would be matched incorrectly according to the above assumption. By defining a word character instead as [\w\-]
the following regex would match the correct words, but unfortunately require replacing a capture group as the first part matches the preceding character due to the lack of lookbehind support in Javascript.
(?:^|[^\w\-])(debt)(?=[^\w\-])
Upvotes: 0
Reputation: 214949
Basically, you're looking for "term followed by not-a-letter but not hyphen":
term = "debt"
re = new RegExp("\\b" + term + "(?=[^\\w-])", "g")
text = "this is debt and debt, debtword and debt-to-income"
console.log(text.replace(re, "<$&>"))
result:
this is <debt> and <debt>, debtword and debt-to-income
Upvotes: 1
Reputation: 59451
debt\b([^\-]|$)
debt
followed by a character other than a hyphen or end of string.
If you want to check left side as well: (^|[^\-])\bdebt\b([^\-]|$)
Upvotes: 1
Reputation: 298046
Just use JavaScript:
var hyphens = 'debt-to-income';
if (hyphens.indexOf('-') == -1) {
// No hyphens
}
Upvotes: 2
Reputation: 348962
Use the following pattern: "debt" not followed by "-to-income"
\bdebt(?!-to-income)
This pattern can easily be expanded to restrict more, for example "debt-of-the-usa
":
\bdebt(?!-to-income|-of-the-usa)
You should not just look for a hyphen, because debt-free
(when debt-free
means nothing) should also be matched, probably.
Upvotes: 1