简体   繁体   English

在javascript中的第一个数字之前获取子字符串

[英]Get a substring before the first figure in javascript

I'm trying to extract all the text until the first figure that appears. 我正在尝试提取所有文本,直到出现第一个数字。 Let's say I have this kind of string "Paris 01 Louvre" . 假设我有这样的字符串"Paris 01 Louvre" I would like to have only "Paris" or if I've "Neuilly sur Seine 03 bla blab" I want to extract "Neuilly sur Seine" . 我只想拥有"Paris"或者如果我拥有"Neuilly sur Seine 03 bla blab"我想提取"Neuilly sur Seine"

I'm struggling with regex in javascript but I can't find the right formula. 我正在用javascript中的正则表达式苦苦挣扎,但找不到正确的公式。

"Neuilly sur Seine 03 bla blab".match(/^\D+(?=\s)/);
// => Neuilly sur Seine

This answer also ensures trailing whitespace isn't captured. 此答案还可以确保不捕获尾随空格。

basic regular expression: 基本正则表达式:

var re = /^([^\d]+)\s/;    
var str = "Neuilly sur Seine 03 bla blab";
console.log( str.match(re) );

^(.+?)\\d

That grabs everything before the first digit ( \\d ). 它将抢占第一个数字( \\d )之前的所有内容。 Play with the regex here . 在这里玩正则表达式

Anything but a number: 除了数字以外的任何东西:

^[^0-9]*
  • ^ is the start-of-line ^是行首
  • [] indicates a character class []表示字符类
  • ^ inside the character class means "invert this class" 字符类中的^表示“反转该类”
  • 0-9 is the numbers 0 to 9, so [^0-9] means any character besides 0 to 9 0-9是数字0到9,因此[^0-9]表示除0到9之外的任何字符
  • * is "zero or more" of the character/class which it follows *是它后面的字符/类的“零个或多个”

这会从字符串的开头抓取所有不是数字的东西。

s.match(/^\D*/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM