How to check if a string includes $sometext$ without numbers in Swift

1 Answer

0 votes
import Foundation

func includeDollarSymbolText(_ input: String) -> Bool {
    // Define regex to match $word$, case-insensitive
    let pattern = "\\$[a-z]+\\$"
    let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)

    // Remove matches from the input
    let range = NSRange(input.startIndex..., in: input)
    let cleanedText = regex.stringByReplacingMatches(in: input, options: [], range: range, withTemplate: "")

    // Check for any remaining dollar symbols
    return !cleanedText.contains("$")
}

print(includeDollarSymbolText("abc xy $text$ z"))            // ok
print(includeDollarSymbolText("abc xy $ text$ z"))           // space
print(includeDollarSymbolText("abc xy $$ z"))                // empty
print(includeDollarSymbolText("abc 100 $text$ z"))           // ok
print(includeDollarSymbolText("abc $1000 $text$ z"))         // open $
print(includeDollarSymbolText("abc xy $IBM$ z $Microsoft$")) // ok
print(includeDollarSymbolText("abc xy $F3$ z"))              // include number
print(includeDollarSymbolText("abc xy $text z"))             // missing close $



/*
run:
   
true
false
false
true
false
true
false
false

*/

 



answered Jul 11, 2025 by avibootz
...