这是我的字符串:
width
我希望使用正则表达式替换字符串中的任何数字(整数或实数是否使用千位分隔符),并获取以下新字符串:
//Your imageView add tapGestureRecognizer event
imageView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
self.imageView.addGestureRecognizer(tapGestureRecognizer)
@objc func tapAction(sender: UITapGestureRecognizer) {
let touchPoint = sender.location(in: self.imageView)
print(touchPoint)
var z1 = touchPoint.x
var z2 = touchPoint.y
print("Before Alert Touched point (\(self.z1), \(self.z2)")
//convert point into Percentage
let z1per = z1 * 100 / self.imageView.frame.size.width
let z2per = z2 * 100 / self.imageView.frame.size.height
print("After Alert Touched point (\(self.z1per), \(self.z2per)")
//whatever you want to add like button or image on tap action.
let btn = UIButton(frame: CGRect(x: touchPoint.x - 15, y: touchPoint.y - 15, width: 30, height: 30))
btn.layer.cornerRadius = 15
btn image = UIImage(named: "marker.png") as UIImage?
btn.setImage(image, for: .normal)
self.imageView.addSubview(btn)
}
如何解决此问题?
答案 0 :(得分:5)
您可以使用此正则表达式捕获数字,
\d+(?:[,.]\d+)*
在这里,\d+
捕获一个具有一个或多个数字的数字,而(?:[,.]\d+)*
可选地捕获多个以逗号或点分隔的数字,并用"$0"
替换它们,其中{{1} }代表整个比赛。
Java代码演示
$0
打印
String s = "\" \"hello\": 0, \"zulu\": 1,234, \"Bravo\": 987.456 \"";
System.out.println(s.replaceAll("\\d+(?:[,.]\\d+)*", "\"$0\""));
此外,您的预期结果似乎缺少输入字符串开头的双引号和空格,并且很可能是拼写错误。