【发布时间】:2017-05-28 03:42:42
【问题描述】:
我使用<pre> 显示了以下多行字符串,如下所示,其中每一行都使用新行表示:
SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem
而我想把build:e9kem解析出来,每次多行的内容都会有所不同。但是每个人都会有build:。
我尝试过:
const regexp = /^build:(.*)$/m;
//stringPar would vary every time
const stringPar = `SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem`;
尝试像这样显示它:
{stringPar.match(regexp)[1])};
它解析正确,但是对于某些多行字符串,当我尝试显示stringPar.match(regexp)[1]之类的字符串时,它会返回Uncaught TypeError: Cannot read property '1' of null,但是当控制台像console.log(stringPar.匹配(正则表达式)[1])。
可能是什么问题?
在此先感谢您,并将投票/接受答案
编辑(在 ReactJS 中)
它基本上是一个反复渲染的组件,其中传递了道具。
export default class tableRow extends Component {
...
render() {
console.log(this.props.stringPar.match(regexp)[1]);
return (
<tr>
<td>
{/*Even tried {this.props.stringPar.match(regexp)[1]==null? " ": this.props.stringPar.match(regexp)} but still getting the same error*/}
<button>{this.props.stringPar.match(regexp)[1]}</button>
<td>
<tr>
)
}
}
【问题讨论】:
-
“对于某些多行字符串”:请举个具体的例子。您的问题也可能与异步代码有关。您能否提供一个代码 sn-p,其
console.log在同一代码块中失败,并说明问题? -
@trincot 请看一下编辑
-
如果你得到的错误是
Uncaught TypeError: Cannot read property '1' of null,那么这意味着this.props.stringPar.match(regexp)的返回返回的是null,而不是数组中的值,因此你尝试的检查可能没有奏效。看起来正则表达式有时会失败。 -
@jonowzz 但我尝试了
{/*Even tried {this.props.stringPar.match(regexp)[1]==null? " ": this.props.stringPar.match(regexp)} but still getting the same error*/}但当我尝试console.log(stringPar.match(regexp)[1])时它仍然有效。 -
您的问题中没有具体的失败示例。请提供一个我们可以用来重现问题的sn-p。可能在 jsfiddle 中。
标签: javascript html regex reactjs react-jsx